• How to access a variable from the main class from another class?
    4 replies, posted
I've got an entity list in the main game class, but I want to access this variable via the entity itself. How would I do this?
That does sound a bit messy - is it right for the entity to know the main game class? What do you want "it" for? If you're worried that you're bundling up a class with rendering code into logic code then seperate it out - have a seperate "world" class and a backend. Would it be kosher to provide it to the entity?
[QUOTE=HubmaN;22023393]That does sound a bit messy - is it right for the entity to know the main game class? What do you want "it" for? If you're worried that you're bundling up a class with rendering code into logic code then seperate it out - have a seperate "world" class and a backend. Would it be kosher to provide it to the entity?[/QUOTE] I already solved it by making the variable static, but your method sounds better, I'll try to do that soon.
If an entity needs to know about the list of other entities, it should be passed in as a parameter -- either by passing the list itself as a parameter, or by putting it into some sort of "game state" object that gets passed in as a parameter. The entity shouldn't be directly accessing things in the main class. It shouldn't even need to [i]know[/i] about the main class.
[QUOTE=Wyzard;22041123]If an entity needs to know about the list of other entities, it should be passed in as a parameter -- either by passing the list itself as a parameter, or by putting it into some sort of "game state" object that gets passed in as a parameter. The entity shouldn't be directly accessing things in the main class. It shouldn't even need to [i]know[/i] about the main class.[/QUOTE] You can also pull it up from a protected method or field in a base class, which in turn received it as a parameter at some earlier point. There are a lot of methods of decoupling around, but first you should really double-check if they need to know about each-other at all. Often the best solution is to branch the coupling into a third module (in this case some sort of factory), knowing about both. Circular dependencies are often the result of bad design.
Sorry, you need to Log In to post a reply to this thread.