Global List to Field List
Monkey Forums/Monkey Programming/Global List to Field List
| ||
I use the "Global List", but I want to use "Field List". In my game a lot of Classes. Some Classes use "Each in" List. There is an easy way to replace the "Global List" to the "Field List"? One way is to move all of the Methods of Classes in the MyGame class. But to use them as a just code. Not as a Method. Then work with this code is not convenient.. Other ideas? |
| ||
If I understand you correctly, you want to move a global list inside a class. If the field is public, you can still use Eachin from outside the class, thus: for local ob:SomeObject = Eachin classInstance.obList ..so long as other classes can access the instance of the class containing the list. |
| ||
Here's an example. I get an error - "Field `GameObjectList` cannot be accessed from here" Import mojo Class GameObject Method Create() Abstract Method Draw() Abstract Method Update() Abstract End Public Class Player Extends GameObject Method Create() End Method Method Draw() End Method Method Update() For Local g:GameObject = Eachin MyGame.GameObjectList If Player(g) Then Print "good" Next End Method End Public Class MyGame Extends App Public Field GameObjectList:List<GameObject> = New List<GameObject> Method OnCreate() Print "go" Local g:Player g = New Player() GameObjectList.AddLast(g) End Method Method OnUpdate() For Local o:GameObject = Eachin GameObjectList o.Update() Next End Method Method OnRender() End Method End Function Main:Int() New MyGame End |
| ||
You need to either create a global reference to MyGame, or make the list global within its class. Either do all of this: [monkeycode]Global game:MyGame ... Public Class Player Extends GameObject ... Method OnUpdate() For Local g:GameObject = Eachin game.GameObjectList If Player(g) Then Print "good" Next End Method ... End ... Function Main:Int() game = New MyGame End[/monkeycode] Or just this: [monkeycode]Public Class MyGame Extends App Global GameObjectList:List<GameObject> = New List<GameObject> ... End[/monkeycode] (where ... indicates snipped code) |
| ||
Thanks. The fact is that I do not want to use global. Global variable in the class, faster than global variables outside the class ? |
| ||
The point is that your game is most likely going to be a singleton, which is why it's OK to store it in a global variable. If the list is related to your game instance, you want it as a field rather than a class level global. |