不确定为什么会收到 NullReferenceError?

Not sure why I'm getting a NullReferenceError?

我正在尝试使用 C# 在 Unity 中创建一个 UI,它显示播放器的某些属性,但是我收到了有关文本对象的 NullReferenceError。我不确定为什么会发生这种情况,因为在运行时没有任何东西应该删除这些对象,而且我很确定这些对象的位置正确。

我有两个几乎完全相同的对象,只是用于两个不同的变量: 当程序启动时,它使用以下方法定位它们:

starstxt = GameObject.Find("Stars").GetComponent<Text>();

我的理解是,这应该在场景中找到具有该名称的文本对象(其中只有 1 个)。

然后显示它:

starstxt.text = ($"Stars: {stars}");

“stars”是从播放器访问的变量。

这是错误发生的行,有谁知道为什么?这是此对象在程序中唯一一次 used/referenced。

我猜测您要获取的星星对象不存在或者您拼错了。所以你试图访问一个等于 Null 的对象。

GameObject.Find() can return null

This function only returns active GameObjects. If no GameObject with name can be found, null is returned. If name contains a '/' character, it traverses the hierarchy like a path name.

但情况可能并非如此,因为 GetComponent 不会抛出任何异常。

问题可能是 GameObject.GetComponent<> can also return null

Returns the component of Type type if the game object has one attached, null if it doesn't.

你应该根据文档中的条件检查是否有任何可以使GetComponentreturn为空的东西。