1
votes

I'm trying to create a simple game to test collision detection, but it won't run properly. It builds fine, but I get this error upon running it: "NullReferenceException: Object reference not set to an instance of an object".

SpriteManager.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace Project_3
{
    public class SpriteManager : Microsoft.Xna.Framework.DrawableGameComponent
    {
        private Game1 _Game1;
        //SpriteBatch for drawing
        SpriteBatch spriteBatch;

        //A sprite for the player and a list of automated sprites
        UserControlledSprite player;
        List<Sprite> spriteList = new List<Sprite>();


        public SpriteManager(Game1 game)
            : base(game)
        {
            // TODO: Construct any child components here
            _Game1 = game;
        }

        public override void Initialize()
        {
            // TODO: Add your initialization code here

            base.Initialize();
        }

        protected override void LoadContent()
        {

            spriteBatch = new SpriteBatch(Game.GraphicsDevice);

            //Load the player sprite
            player = new UserControlledSprite(
                Game.Content.Load<Texture2D>("Images/bill"),
                Vector2.Zero, 10, new Vector2(6, 6));

            //Load several different automated sprites into the list
            spriteList.Add(new AutomatedSprite(
                Game.Content.Load<Texture2D>("Images/kit"),
                new Vector2(150, 150), 10, Vector2.Zero));
            spriteList.Add(new AutomatedSprite(
                Game.Content.Load<Texture2D>("Images/kit"),
                new Vector2(300, 150), 10, Vector2.Zero));
            spriteList.Add(new AutomatedSprite(
                Game.Content.Load<Texture2D>("Images/beast"),
                new Vector2(150, 300), 10, Vector2.Zero));
            spriteList.Add(new AutomatedSprite(
                Game.Content.Load<Texture2D>("Images/beast"),
                new Vector2(600, 400), 10, Vector2.Zero));

            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            // Update player
            player.Update(gameTime, Game.Window.ClientBounds);

            // Update all sprites
            foreach (Sprite s in spriteList)
            {
                s.Update(gameTime, Game.Window.ClientBounds);
            }

            base.Update(gameTime);
        }

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

            // Draw the player
            player.Draw(gameTime, spriteBatch);

            // Draw all sprites
            foreach (Sprite s in spriteList)
                s.Draw(gameTime, spriteBatch);

            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}

The line that throws the exception is player.Update(gameTime, Game.Window.ClientBounds); from SpriteManager. The full exception message is "An unhandled exception of type 'System.NullReferenceException' occurred in Project 3.exe. Additional information: Object reference not set to an instance of an object."

UserControlledSprite.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Project_3
{
class UserControlledSprite : Sprite
{
    // Movement stuff
    MouseState prevMouseState;

    // Get direction of sprite based on player input and speed
    public override Vector2 direction
    {
        get
        {
            Vector2 inputDirection = Vector2.Zero;

            // If player pressed arrow keys, move the sprite
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
                inputDirection.X -= 1;
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
                inputDirection.X += 1;
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
                inputDirection.Y -= 1;
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
                inputDirection.Y += 1;

            // If player pressed the gamepad thumbstick, move the sprite
            GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);
            if (gamepadState.ThumbSticks.Left.X != 0)
                inputDirection.X += gamepadState.ThumbSticks.Left.X;
            if (gamepadState.ThumbSticks.Left.Y != 0)
                inputDirection.Y -= gamepadState.ThumbSticks.Left.Y;

            return inputDirection * speed;
        }
    }

    public UserControlledSprite(Texture2D textureImage, Vector2 position, int collisionOffset, Vector2 speed)
    {
    }

    public override void Update(GameTime gameTime, Rectangle clientBounds)
    {
        // Move the sprite based on direction
        position += direction;

        // If player moved the mouse, move the sprite
        MouseState currMouseState = Mouse.GetState();
        if (currMouseState.X != prevMouseState.X ||
            currMouseState.Y != prevMouseState.Y)
        {
            position = new Vector2(currMouseState.X, currMouseState.Y);
        }
        prevMouseState = currMouseState;

        // If sprite is off the screen, move it back within the game window
        if (position.X < 0)
            position.X = 0;
        if (position.Y < 0)
            position.Y = 0;
        if (position.X > clientBounds.Width - 150)
            position.X = clientBounds.Width - 150;
        if (position.Y > clientBounds.Height - 150)
            position.Y = clientBounds.Height - 150;

        base.Update(gameTime, clientBounds);
    }
}
}

I'm not sure why it isn't working. I've tried a bunch of different things, but since I'm new to xna, I'm probably missing something simple.

Any help would be greatly appreciated.

EDIT: Forgot to add Sprite.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Project_3
{
    abstract class Sprite
    {
    // Stuff needed to draw the sprite
    Texture2D textureImage;

    // Collision data
    int collisionOffset;

    // Movement data
    protected Vector2 speed;
    protected Vector2 position;

    // Abstract definition of direction property
    public abstract Vector2 direction
    {
        get;
    }

    public Sprite()
    {
    }

    public Sprite(Texture2D textureImage, Vector2 position, int collisionOffset, Vector2 speed)
    //: this(textureImage, position, collisionOffset, speed)
    {
    }

    public virtual void Update(GameTime gameTime, Rectangle clientBounds)
    {

    }

    public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
    {
        // Draw the sprite
        if (textureImage != null)
        {
            spriteBatch.Draw(textureImage, position, Color.White);
        }
    }

    // Gets the collision rect based on position, framesize and collision offset
    public Rectangle collisionRect
    {
        get
        {
            return new Rectangle(
                (int)position.X + collisionOffset,
                (int)position.Y + collisionOffset,
                150 - (collisionOffset * 2),
                150 - (collisionOffset * 2));
        }
    }


    public Game1 _Game1 { get; set; }
}
}
2
try Game.Content.Load<Texture2D>("/Images/bill") Note the / before Images - Alekstim
The Visual Studio Debugger allows you to hover over variables to see their value. Do that, and find out which variable is null that is being dereferenced. - Robert Harvey
'player' is null. I've tried a few different things, but I'm not sure how to debug something like this. - Richard A
Have you made sure that the player texture is added to the content project? Have you then made sure that the directory is correct? If all of the above, try this: Game.Content.Load<Texture2D>(@"Images/bill") - Mohammed Hossain
Setting Game.Content.Load<Texture2D>(@"Images/bill") fixed that error, but now I'm getting the same error at player.Update(gameTime, Game.Window.ClientBounds); in the Update method. - Richard A

2 Answers

0
votes

You are not instantiating position. You pass the position variable into the contructor of UserControlledSprite but do not apply it to a variable within the scope of the class. You need to declare another variable to hold the position variable, which is only visible to the constructor method.

This means that the first time the UserControlledSprite object calls Update, then position += direction; will throw the NullReferenceException. To be honest, I don't know how you didn't get a compile time error, as position will not exist in the context of Update, unless you haven't shown us the whole code.

0
votes

Sorry, I can't make a comment yet.

It doesn't seem like when you create player (a UserControlledSprite) that you then call the Sprite constructor from "UserControlledSprite(...parameters...)".

public UserControlledSprite(Texture2D textureImage, Vector2 position, int collisionOffset, Vector2 speed)
{
}

might need to be:

public UserControlledSprite(Texture2D textureImage, Vector2 position, int collisionOffset, Vector2 speed) 
    : base(TextureImage, position, collisionOffset, speed)
{
}

It would also be useful to set the data that you pass through. So you pass in textureImage, position, collisionOffset, and speed. I see that you have the variables in the Sprite class, but I don't see you setting them upon creating them with the constructor. Unless, tell me if this is the case please, passing in the parameter with the same name as the variable automatically sets it? If that isn't the case, then make sure you actually set position, collisionOffset, speed, and textureImage in the sprite class to their actual passed parameters. I always thought you can't have the same name in parameters as you do as variables of the class.

So you'd have to do (if the above is true):

public UserControlledSprite(Texture2D _textureImage, Vector2 _position, int _collisionOffset, Vector2 _speed) 
    : base(_textureImage, _position, _collisionOffset, _speed)
{
    //Do this either here or in Sprite. 
    this.textureImage = _textureImage;
    this.position = _position;
    this.collisionOffset = _collisionOffset;
    this.speed = _speed.
}    

I think the above (immediately above this) detail isn't so important for your current issue. I think it has more to do with the constructor, but I'm not sure. I don't have VS on here and just want to try and help you out for right now.

Anyway, I hope that helps. Sorry, I'd comment if I could. Sadly I can't yet.