Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I've just begun working on my game and I don't know how to organize my game in separate classes, because I need some variables/methods to be available to every class. I have a screen manager class and some screen classes which inherit a base screen class. But I can't access the screen manager's methods without making it a singleton, and I would like to avoid this solution. And I would like some game variables or methods to be available from any other class, but I can't do it without making them static. Let's say I have variable which stores the game difficulty throughout the game screens. If I would like to implement such a thing I would need to make it static in the Game1 class. Short story, I don't know how to make methods/variables global without making them static.

share|improve this question
    
Since you're using XNA a common way would be to register a class as a game service, then give all your dependent classes a reference to the game object so they could find the classes/services they need. –  George Duckett Aug 6 '12 at 10:54

2 Answers 2

up vote 1 down vote accepted

In case your reason for not making them static is that you see a possibility for needing to have several instances of them in the future then I think using singletons is an elegant solution.

Assuming that you might need to make several instances of these classes in the future you could store a reference to them in a wrapper class and send this as parameter in the constructor of those classes that need them. Alternatively you could send references as parameters to whatever methods need them (like draw or update or whatever). However having a lot of circular references might be a "bad smell" ie a warning sign that somthing needs to be redesigned...

share|improve this answer
    
At any time there won't be more than a single instance of that class, so I'm going to use a singleton. –  mmimaa Aug 6 '12 at 14:49

There is often a temptation to make some parts of your application globally accessible, most commonly by making them static or by using the Singleton pattern or the Registry pattern. Do not follow that temptation.

Instead, try to reduce dependencies in your OO design. Then pass the objects explicitly to whatever other objects and methods need it.

This will not only lead to more elegant, maintainable, and extendable code. It is also a requirement for your code to be testable. Have a look at http://www.youtube.com/watch?v=-FRm3VPhseI for more information on this.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.