I'm currently working on a 2D game engine in XNA, and I am very interested in architecture, and how best to let my game objects communicate.
I know a lot of people use a Singleton design but I believe that this is more of a "counter-architecture" way of doing things, as every class will have access to the Singleton.
I was comtemplating using a Service-type architecture to allow for my Input, Sound, etc Manager classes to be available, but this is essentially the same problem as the Singleton as all the Classes are available to 'whoever' wants them.
I could of course pass references to the objects when they are needed, but this is bloated.
I wonder if making the 'Services' only allow certain objects to subscribe would be possible?
So is there a better way to make your classes available?
Or am I searching for an answer that doesn't have a question?
Answer
When you're writing a game, you're better off writing a game than worrying too much about having the perfect architecture. There's nothing really wrong with having singletons and global variables in a game. Far better to have less and more flexible code than for it to be perfect.
I personally find that Singleton is a pattern to be avoided. Most of the time you should be using a static class or member instead of a singleton. See, for example, the Mouse
and Keyboard
and MediaPlayer
classes in XNA. These are all simply static classes which are globally accessible.
I would query your need for a "sound manager", seeing as SoundEffect
s are stand-alone. And ContentManager
is already the only thing you need to "manage" them.
You don't really need to write a services architecture, because XNA already provides one (see Game.Services
).
If it seems like it would help, there's no reason why you can't just add a public static MyGame theGame
member to your Game
class and effectively turn it into a singleton. For the simple reason that there is never reasonably going to be more than one instance of your game class. Then you can make its members public (Content
and Services
already are) and access them globally, if it makes sense. This is simple. You can always change it to something more complicated later!
Making only your Game
class a globally accessible also keeps the global access point localised to one place in the code, making it easier to locate when you want to "un-globalify" something later.
What I would very much avoid is making true Singleton classes that can only be instanced once. For example: don't make a map class that you can only create one instance of: what if you want to add background loading of the next map later? (Or the player class - for multiplayer, and so on).
The best example of this "global but not singleton" in XNA is ContentManager
. You've got Game.Content
which is effectively global. But you can also create more instances of ContentManager
, which can be owned by whatever you like (levels, screens, whatever) and will operate independently.
No comments:
Post a Comment