How to use Game State Management

May 16, 2011 at 11:49 PM

Hello,

I am just starting XNA and I am wondering how GameState should communicate with game resources.

Would it be good idea to create resources(textures and models) needed in the GameState's OnEntered method? Doing so probably requires passing the ContentManager to GameState as parameter via constructor? Should all other references(SpriteBatch...) also be passed in constructor or is there some better mechanism available?

Coordinator
May 17, 2011 at 9:34 AM

Game states are created only after the game has started, so you can just load/create your assets in the constructor and free them again in Dispose(). You only have to take care not to Push() the initial game state before the Game has been fully initialized (good places are the end of the Game class' constructor or inside Game.LoadContent()).

Yes, references should be passed to constructor of each game state. You can either use XNA's architecture and provide the game state with an IServiceProvider from which it can pick up its required components or you can pass the required components directly, which makes it easier to see which services a game state consumes and allows for a very elegant integration with dependency injectors.

I have, in some cases, created a reference container class if many game components required the same set of references. I described that concept in an article on my website: Code Better: Reference Containers for Change-Resistant Constructors

May 17, 2011 at 10:01 PM

Thanks for ideas and clarification.

This isn't actually about this nice library of yours but I'll ask anyways. Do you prefer loading all or most assets at the very beginning of the game or later on when assets are actually going to be used? Also would it make much difference if all/most states are created in the beginning of game or only when necessary? It seems to me it wouldn't matter much for smaller game but for larger game it could be quite important? It seems there's a lot to consider when using XNA as this isn't as plug n' play as some other game engines I've played with.