You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Unity中NullReferenceException(对象未实例化)错误?

解决Unity中Text赋值的NullReferenceException错误

问题现象

控制台抛出NullReferenceException: Object reference not set to an instance of an object错误,错误定位到脚本中诸如moneyText.text = money.ToString()的Text赋值代码行;调整Start方法里赋值语句的顺序后,错误会指向当前最靠前的那条同类赋值语句。

问题代码

第一段代码:

public void Start()
{
    money = PlayerPrefs.GetInt("Money");
    earnedMoney = PlayerPrefs.GetInt("earnedMoney");
    record = PlayerPrefs.GetInt("record");
    live = PlayerPrefs.GetInt("live");
    money += earnedMoney;
    PlayerPrefs.SetInt("Money", money);
    PlayerPrefs.SetInt("Score", 0);
    PlayerPrefs.SetInt("earnedMoney", 0);
    moneyText.text = money.ToString();
    recordText.text = record.ToString();
    liveText.text = live.ToString();
}

第二段代码:

public void Start()
{
    money = PlayerPrefs.GetInt("Money");
    earnedMoney = PlayerPrefs.GetInt("earnedMoney");
    record = PlayerPrefs.GetInt("record");
    live = PlayerPrefs.GetInt("live");
    money += earnedMoney;
    PlayerPrefs.SetInt("Money", money);
    PlayerPrefs.SetInt("Score", 0);
    PlayerPrefs.SetInt("earnedMoney", 0);
    liveText.text = live.ToString();
    moneyText.text = money.ToString();
    recordText.text = record.ToString();
}

修复方案

  • 检查Text组件引用赋值:moneyText、recordText、liveText这些脚本声明的Text变量,必须在Unity编辑器的Inspector面板中,把场景中对应的UI Text组件拖到脚本的对应变量插槽里。未赋值的变量在运行时会是null,赋值text属性时必然报错。
  • 添加空值检查避免崩溃:在赋值前先判断组件是否存在,既避免空引用崩溃,也能明确排查出哪一个组件未正确赋值:
    if(moneyText != null) moneyText.text = money.ToString();
    if(recordText != null) recordText.text = record.ToString();
    if(liveText != null) liveText.text = live.ToString();
    
  • 确认UI对象的激活状态:确保moneyText、recordText、liveText所在的GameObject在游戏启动时(Start方法执行时)处于激活状态。如果父对象或自身被禁用,组件引用会无法获取,导致null。
  • 调整初始化时机(可选):若怀疑是脚本执行顺序问题,可将组件引用的初始化逻辑(比如通过Find或GetComponent获取组件)放在Awake方法中,Start方法仅负责数据赋值操作。不过更推荐手动在Inspector赋值引用,避免查找逻辑带来的潜在问题。

内容的提问来源于stack exchange,提问作者Relid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:33:20