NullReferenceException: OnDestroy()函数错误



在我的游戏中,我有硬币,在我的硬币脚本中,我有一个OnDestroy()函数,但我得到这个错误"NullReferenceException:对象引用未设置为对象的实例coinscript。OnDestroy () (at Assets/scripts/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;
}
}
}

你需要进入你所附加脚本的对象的属性,并为Game Manager分配一个带有gamemanager脚本的对象。

正如ted所说,这可能是因为你还没有设置GameManager from inspector。你需要拖拽一个带有gamemanager组件的gameObject。

但是我建议将plusScore函数设置为静态并且不使用对象来调用它,如果你将它设置为静态你还需要设置一个变量来存储静态分数,就像这样

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

然后像这样调用它:

gamemanager.plusScore(10);

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

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

最新更新