XNA SpriteBatch instantiation issue
I've been practicing certain techniques in XNA and lately came across an issue that's just confusing me. I've been using th开发者_如何学Pythonis 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
)- Update and draw calls
(This is not the full list, by the way.)
So I would guess that, by adding the game component in your game's LoadContent
function, the LoadContent
in your game component is not being called so its SpriteBatch
is not being created. You could check this by adding a breakpoint in your game component's LoadContent
function.
Generally you want to create and add your game components in your game's Initialize
function.
(Also you should, and possibly need to, call the respective base
functions in LoadContent
and UnloadContent
.)
Personally I prefer to avoid using DrawableGameComponent
and just make my own free-standing class. This lets me share instances of SpriteBatch
more directly (rather than having to create ones for each component) and it lets me more explicitly control the order things are called in.
精彩评论