为什么在 Unity C# 中尝试创建 HealthPack 时出现 NullReferenceException?

Why am i Getting NullReferenceException when trying to create a HealthPack in Unity C#?

好的,伙计们,我又遇到了一些代码问题。基本上,一旦我开始并尝试创建一个 Health Pack,它就会抛出一个错误:

NullReferenceException: 对象引用未设置为对象的实例 HealthSpawnerScript.Update () (位于 Assets/Scripts/HealthSpawnerScript.cs:31)

下面是我 运行 的代码。游戏对象 PlayerController 包含一个用于 return Player Health 的方法,名为 PlayerHealth()。在清醒状态下,我设置 playerController 来查找我要查找的脚本和方法。然后在更新中,我试图调用该方法并将其分配给一个变量,以便稍后在脚本中使用。我知道这应该很简单,但伙计们我脑袋放屁了。

public PlayerController playerController;
private int healthHolder;

void OnAwake()
{
    playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();

}
// Use this for initialization
void Start () 
{
    //set healthExist to false to indicate no health packs exist on game start
    healthExist = false;

    //playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();
}

// Update is called once per frame
void Update () 
{
    healthHolder = playerController.PlayerHealth();

没有名为 OnAwake 的 Unity 回调函数。您可能正在寻找 Awake 函数。

如果问题已解决但问题仍然存在,则必须将代码分成几部分并找出失败的原因。

playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();

应该改为

void Awake()
{
    GameObject obj = GameObject.Find("PlayerHealth");
    if (obj == null)
    {
        Debug.Log("Failed to find PlayerHealth GameObject");
        return;
    }

    playerController = obj.GetComponent<PlayerController>();
    if (playerController == null)
    {
        Debug.Log("No PlayerController script is attached to obj");
    }
}

因此,如果 GameObject.Find("PlayerHealth") 失败,则意味着场景中不存在具有该名称的游戏对象。请检查拼写。

如果 obj.GetComponent<PlayerController>(); 失败,则没有名为 PlayerController 的脚本附加到 PlayerHealth 游戏对象。简化您的问题!