I’ve been practicing certain techniques in XNA and lately came across an issue that’s just confusing me. I’ve been using this technique for a few of my Windows Game Projects and all of a sudden now theres a problem, I think i’m overlooking something…
So I created a fresh Windows Game Project and added a XNA Game Componant to the project, added the componant to the Game1.cs file. Created and instantiated a SpriteBatch variable in the Componant then tried to draw a simple texture to test the spriteBatch.
Here’s a picture of the runtime error I get: http://twitpic.com/3jp8t1
…and the full source of the two files: pastebin.com/rFRkGKXJ
Off the top of my head (you can double-check me using Reflector), the order of calls during XNA initialisation is this:
Initialize()in your game classLoadContent()in your game components (called fromGame.Initialize)LoadContent()in your game class (called fromGame.Initialize)(This is not the full list, by the way.)
So I would guess that, by adding the game component in your game’s
LoadContentfunction, theLoadContentin your game component is not being called so itsSpriteBatchis not being created. You could check this by adding a breakpoint in your game component’sLoadContentfunction.Generally you want to create and add your game components in your game’s
Initializefunction.(Also you should, and possibly need to, call the respective
basefunctions inLoadContentandUnloadContent.)Personally I prefer to avoid using
DrawableGameComponentand just make my own free-standing class. This lets me share instances ofSpriteBatchmore directly (rather than having to create ones for each component) and it lets me more explicitly control the order things are called in.