Nick
Nick

Reputation: 177

XNA NullReferenceException I think LoadContent won't run

I have an xna game that I am creating, and it compiles fine, but a nullreferenceexception is thrown when it reaches spriteBatch.Begin(); in my spritemanager class (which is a drawable game component). I think loadContent is not running, leaving the spritebatch uninitialized, but i'm not sure how to get it to run.

SpriteManager LoadContent Code:

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(Game.GraphicsDevice);  

        player = new Player(Game.Content.Load<Texture2D>("Images/asteroids_player"),
                            new Vector2(Game.Window.ClientBounds.X / 2, Game.Window.ClientBounds.Y / 2),
                            Vector2.Zero,
                            0f,
                            new Point( 27, 40 ),
                            new Point( 1, 1 ),
                            new Point( 1, 2 ));

        asteroidList = new List<Asteroid>();

        base.LoadContent();
    }

SpriteManager Draw code:

    public override void Draw(GameTime gameTime)
    {
        spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);  // error thrown here

        player.Draw(gameTime, spriteBatch);

        spriteBatch.End();

        base.Draw(gameTime);
    }

Game1 code:

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    SpriteManager spriteManager;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // Creates and loads a SpriteManager to update/draw sprite objects
        spriteManager = new SpriteManager(this);
        Components.Add(spriteManager);

        base.LoadContent();
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here

        base.Draw(gameTime);
    }

Upvotes: 1

Views: 497

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32587

Add the SpriteManager component in the Initialize() method before the call to base.Initialize().

Upvotes: 2

Related Questions