简体   繁体   English

XNA空参考异常

[英]XNA Null Reference Exception

Everything was working fine on this game I am making, but now I started getting NullReferenceException errors on some of my code. 我制作的这款游戏一切正常,但是现在我的一些代码开始出现NullReferenceException错误。

Here I define a Vector2 and a Texture2D: 在这里,我定义了Vector2和Texture2D:

Vector2 startButtonPosition;
Texture2D startButton;

And then in the Initialise() method: 然后在Initialise()方法中:

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. 运行此命令时,在startButtonPosition初始化时收到NullReferenceException错误,表明该对象引用未设置为对象的实例。 Yet it is. 是的

Either graphics or startButton , or one of their properties you are using, is set to null. graphicsstartButton或您使用的属性之一都设置为null。

You can check this by hovering over the variables when an exception is thrown (Click break ) 您可以通过在引发异常时将鼠标悬停在变量上来进行检查(单击break

Remember just because you declare startButton as a variable, does not mean it is set to a value. 请记住,仅因为将startButton声明为变量,并不意味着将其设置为值。 You need to initialize it. 您需要初始化它。 (Ex: startButton = Content.Load<Texture2D... ) (例如: startButton = Content.Load<Texture2D...

The code you provided is trying to initialize 'startButtonPosition' using 'startButton'. 您提供的代码试图使用“ startButton”初始化“ startButtonPosition”。 The problem is, you never initialize 'startButton' therefore it is 'null'. 问题是,您永远不会初始化“ startButton”,因此它为“ null”。

@Pierre-Luc Pineault is right to suggest What is a NullReferenceException and how do I fix it? @ Pierre-Luc Pineault可以建议什么是NullReferenceException以及如何解决它?

Here's a link to initialize 'startButton'. 这是初始化“ startButton”的链接。 Texture2D Constructor Texture2D构造函数

I haven't used Texture2D but I'm assuming it'll look something like this: 我没有使用Texture2D,但我假设它看起来像这样:

Texture2D startButton = new Texture2D(graphics.GraphicsDevice, width, height);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM