当游戏处于播放模式时 GameObject 被丢弃 "NullReferenceException object reference not set an instance or object"

GameObject gets dropped when game is in play mode "NullReferenceException object reference not set an instance or object"

我有一个名为 TimeManager 的空对象。在对象上,我附上了以下脚本。然后我将文本 UI GameObject "MyTime" 拖到 Text Timer 字段。当游戏不玩时,一切都会显示出来。当我点击播放时,对象变为未分配状态。

如果在玩游戏时,我可以将 "MyTime" 拖到文本计时器,然后就可以正常工作了。我不确定为什么当我点击播放时它会下降。

public class TimeLeft : MonoBehaviour
{


public float myCoolTimer = 10;
public Text timerText;

public static TimeLeft instance = null;

void Awake ()
{
    if (instance == null) {
        instance = this;
    } else if (instance != this) {
        Destroy (this.gameObject);
    }

}

void Start ()
{
    timerText = GetComponent<Text> ();

}


public void Update ()
{
    //Timer
    myCoolTimer -= Time.deltaTime;
    timerText.text = myCoolTimer.ToString ("f2");

}

注意:我需要单例,因为我在其他脚本中使用它。

TimeManager 对象与包含文本组件的游戏对象不同。

void Start ()
{
    timerText = GetComponent<Text> ();
}

Start 方法在与 TimeManager 相同的对象上查找 Text 组件,发现 none 因此它分配 null。

由于您正在拖动组件,请从头开始删除该行,或者检查它是否为空并查找对象。

void Start ()
{
    if(timerText != null){
       GameObject timerObject = GameObject.Find("TextObjectName");
       timerText = timerObject.GetComponent<Text> ();
    }
}