【问题标题】:NullReferenceException problem in Unity when object is not null [duplicate]当对象不为空时,Unity中的NullReferenceException问题[重复]
【发布时间】: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); 如何确定它是从您的脚本中设置的? ,也许它来自其他脚本,而您认为它来自您的脚本。

标签: unity3d


【解决方案1】:

在哪里偶然定义的tractionLastId?是否正在初始化?由于您已经在 Start 函数内部进行了空值检查,因此请尝试重构 RegisterAttraction 函数,使其看起来像:

public void RegisterAttraction(GameObject newAttraction)
    {

            Debug.Log("Attempting to register gameObject");
            attractionLastID++;
            sceneAttractions.Add(attractionLastID, newAttraction);
            Debug.Log("Registered");
    }

我强烈建议在 RegisterAttraction 的开始卷曲处设置断点。逐步进行并将鼠标悬停在每个变量上以查看哪个为空。

【讨论】:

  • 原来问题出在sceneAttractions - 它没有足够早地初始化。感谢您建议断点!
猜你喜欢
  • 1970-01-01
  • 2022-08-13
  • 2013-03-04
  • 2021-11-29
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 2014-07-21
  • 2023-03-20
相关资源
最近更新 更多