Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphicsDevice is null in my XNA Windows Game project

I have just started trying to make a simple game with XNA 3.1 to help myself learn C# and XNA. I have run into a bit of an interesting problem, however. In all of the tutorials, one is supposed to pass GraphicsDevice when instantiating a new spriteBatch object like this:

spriteBatch = new SpriteBatch(GraphicsDevice);

One might even do this:

GraphicsDevice objGraphics = new graphics.GraphicsDevice;
spriteBatch = new SpriteBatch(objGraphics);

where graphics is the GraphicsDeviceManager. However, no matter which version I try, I always get an ArgumentNullException when I try to pass the GraphicsDevice object to spriteBatch's constructor. Almost every tutorial I have found gives the first one and only one mentioned the second option. Has anyone else run into a similar error or know what could be causing this? I am working in Windows 7 x64 with Visual Studio 2008.

EDIT:

I seem to have found the problem. I was trying to execute that code in the constructor (which is where I assumed it was supposed to go). I did a bit of Googling and found the answer here. Thanks for the help.

like image 465
mnuzzo Avatar asked Oct 28 '25 11:10

mnuzzo


1 Answers

I'm putting the answer here for completeness' sake.

The code

spriteBatch = new SpriteBatch(GraphicsDevice);

Can only be executed in the LoadContent() method of the Game class. I was putting it in the constructor at which point the GraphicsDevice object has not been defined according to one of the answers to this question.

like image 196
mnuzzo Avatar answered Oct 31 '25 03:10

mnuzzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!