简体   繁体   English

对象引用未设置为对象的实例(C#)

[英]Object reference not set to an instance of an object (C#)

I can't seem to get this working, I'm getting an error once opening my c# project file (.exe) and it says "object reference not set to an instance of an object". 我似乎无法正常工作,打开我的C#项目文件(.exe)后出现错误,并显示“对象引用未设置为对象实例”。 Here's the line and the one below it. 这是线和下方的线。

// Update the actual position

Actor.Position = new Vector3(
                        Actor.PositionToSet.X, 
                        Actor.PositionToSet.Y, 
                        (Math.Round(
                            GetUserStepHeight(
                                Actor.PositionToSet),
                                1)));

Actor.PositionToSet = null;

The possibility is, either 1. Actor is null or 2. Actor.PositionToSet is null . 可能是1. Actornull或2. Actor.PositionToSetnull

To check, either have this: 要进行检查,可以使用以下方法:

if(Actor == null){
    System.Console.WriteLine("Actor is NULL");
}

if(Actor.PositionToSet == null){
    System.Console.WriteLine("Actor.PositionToSet is NULL");
}

or use the LINE BY LINE debugger in Visual Studio. 或在Visual Studio中使用LINE BY LINE调试器。

Here is a piece of advice I got years ago: 这是我几年前得到的一条建议:

  1. Think before you code, and build a mental model of the code, then when things break, just reflect on what went wrong without looking at the code. 在编写代码之前先三思,并建立代码的思维模型,然后在事情破裂时,只需思考一下出了什么问题,而无需查看代码。

  2. Unit test your code, make it a standard practice of your coding methodology. 对代码进行单元测试,使其成为编码方法的标准做法。 This will save you years of debugging time. 这将节省您数年的调试时间。

Please check that Actor or Actor.PositionToSet is not null. 请检查ActorActor.PositionToSet不为null。 That is the only reason. 那是唯一的原因。

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

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