1

I am attempting to create an asteroids game for university. However, when I am debugging the game, I keep getting an error stating that 'Object reference not set to an instance of an object.

The line of code that the debugger states where the error is, is:

Asteroidorigin.X = texture.Width / 2;
Asteroidorigin.Y = texture.Height / 2;

Asteroidorigin and texture are defined like this:

public Vector2 texture;
public Vector2 Asteroidorigin;

The code above looks all ok to me, so any help on this matter would be appreciated, Cheers

3
  • 2
    Probably texture is null Commented Mar 29, 2014 at 19:07
  • I'm guessing the above code should probably read: public Texture2D texture; // not a Vector2 Commented Mar 29, 2014 at 22:28
  • yeah thats what it is supposed to read Commented Mar 30, 2014 at 10:10

1 Answer 1

1

From the code you posted, texture has not been loaded yet. This code needs to be run after LoadContent() assigns that texture to an asset coming through the content pipeline.

If the code is run repeatedly, and it doesn't matter if it doesn't run the first time it is called, you could just add a null check:

if (texture != null)
{
    Asteroidorigin.X = texture.Width / 2;
    Asteroidorigin.Y = texture.Height / 2;
}
Sign up to request clarification or add additional context in comments.

3 Comments

The asteroidorigin code is within an update method which is located below the LoadContent method where my texture is being loaded
Then performing the null check should be sufficient (since Update is called all the time). Just make sure anything else dependent on these properties being set is in the null check as well. If it is always null then make sure the load isn't failing in LoadContent
Great! When you feel this question is answered, I would appreciate you "accepting" this answer (assuming it is the best of course!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.