NullReferenceException: OnDestroy() 函数错误

NullReferenceException: OnDestroy() function error

在我的游戏中,我有硬币,在我的硬币脚本中,我有一个 OnDestroy() 函数,但我收到此错误“NullReferenceException:未将对象引用设置为对象的实例 coinscript.OnDestroy ()(位于 Assets/Scrips/coinscript.cs:9)"

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class coinscript : MonoBehaviour
{   public gamemanager GameManager;
    void OnDestroy() 
    {
       GameManager.plusScore(10);// FindObjectOfType<gamemanager>().pluseScore(10); gets the same error
    }

}

在 KiynL

的帮助下修复了它
using System.Collections.Generic;
using UnityEngine;

public class coinscript : MonoBehaviour
{   public gamemanager GameManager;
    bool destroyed = false;
    void OnDestroy() 
    {
       if (destroyed = false) 
       {
           GameManager.plusScore(10);
           destroyed = true;
       }
    }

}

您需要进入您将该脚本附加到的任何对象的属性,并为游戏管理器分配一个附加了 gamemanager 脚本的对象。

这是因为对象可能在一帧内被销毁多次。修复它。

void OnDestroy() 
{
    if (gameObject) GameManager.plusScore(10);
}

正如 ted 所说,这可能是因为您尚未从检查器中设置 GameManager。您需要拖动一个上面有 gamemanager 组件的游戏对象。

但我建议将 plusScore 函数设为静态并在没有对象的情况下调用它,如果你将其设为静态,你还必须将存储分数的变量设为静态,例如:

public class gamemanager : MonoBehaviour
{
    static int Score = 0;
    public static void plusScore(int score)
    {
        Score += score;
    }
}

然后这样调用它:

gamemanager.plusScore(10);