【发布时间】:2019-09-27 02:40:05
【问题描述】:
我正在尝试对以下导致 NullReferenceException 的代码进行故障排除。本质上,当创建一个对象时,我试图让它在我的游戏管理器类中注册。这是我的对象的组件:
void Start()
{
Debug.Log("Registering");
if (gameObject != null)
{
GameMngr.Instance.RegisterAttraction(gameObject);
}
else
{
Debug.Log("Gameobject null");
}
}
在我的游戏管理器中,我有以下内容:
public void RegisterAttraction(GameObject newAttraction)
{
if (newAttraction != null)
{
Debug.Log("Attempting to register gameObject");
attractionLastID++;
sceneAttractions.Add(attractionLastID, newAttraction);
Debug.Log("Registered");
}
else
{
Debug.Log("unable to register: null provided");
}
}
我的控制台输出如下:
- 注册
- 正在尝试注册游戏对象
- NullReferenceException
我的代码显示尝试注册 gameObject 行的事实使我相信我的 newAttraction 变量不为空。为什么我会收到错误消息?
感谢您的帮助
【问题讨论】:
-
打印游戏对象 instanceID ,可能不是同一个游戏对象??
-
“当对象不为 null 时 Unity 中的 NullReferenceException 问题”——当引用实际上不是 null 时,您可能会得到
NullReferenceException的想法只是荒谬的。空值可能不是您认为应该的值。但是肯定有一个你试图取消引用的空值。有关如何调试问题的完整详细信息,请参阅建议的副本。 -
GameMngr.Instance.RegisterAttraction(gameObject);如何确定它是从您的脚本中设置的? ,也许它来自其他脚本,而您认为它来自您的脚本。 -
还要确保你在 Unity 中 never use
== null/!= nullfor references of typeObject!
标签: unity3d