0

Everything was working fine on this game I am making, but now I started getting NullReferenceException errors on some of my code.

Here I define a Vector2 and a Texture2D:

Vector2 startButtonPosition;
Texture2D startButton;

And then in the Initialise() method:

startButtonPosition = new Vector2((graphics.GraphicsDevice.Viewport.Width - startButton.Width) / 2, 150); 

When I run this, I get the NullReferenceException error on the startButtonPosition initialisation saying that the object reference was not set to an instance of an object. Yet it is.

user2681474
  • 15
  • 1
  • 7

2 Answers2

0

Either graphics or startButton, or one of their properties you are using, is set to null.

You can check this by hovering over the variables when an exception is thrown (Click break)

Remember just because you declare startButton as a variable, does not mean it is set to a value. You need to initialize it. (Ex: startButton = Content.Load<Texture2D...)

Cyral
  • 13,999
  • 6
  • 50
  • 90
0

The code you provided is trying to initialize 'startButtonPosition' using 'startButton'. The problem is, you never initialize 'startButton' therefore it is 'null'.

@Pierre-Luc Pineault is right to suggest What is a NullReferenceException and how do I fix it?

Here's a link to initialize 'startButton'. Texture2D Constructor

I haven't used Texture2D but I'm assuming it'll look something like this:

Texture2D startButton = new Texture2D(graphics.GraphicsDevice, width, height);
Community
  • 1
  • 1
christo8989
  • 6,442
  • 5
  • 37
  • 43