Unity中Stopwatch秒表脚本报NullReferenceException错误排查
问题根因
这个空引用报错是运行时错误,和Visual Studio的静态检查不冲突——报错指向第28行currentTimeText.text = time.Seconds.ToString();,说明执行到这行时currentTimeText字段没有赋值,是null。
你说功能运行完全正常但依然报错,几乎可以确定是**Stopwatch脚本在当前场景被重复挂载了两次**:其中一个实例上你正确拖拽赋值了Text组件,负责正常显示计时;另一个多余挂载的实例上currentTimeText字段是空的,每帧执行Update时就会抛出这个错。
排查方法
直接点击Unity控制台里的这条报错,Unity会自动定位到抛出错误的对应游戏对象,你检查这个对象上挂载的Stopwatch组件:
- 如果是多余挂载的脚本,直接删除该组件即可
- 如果是需要保留的组件,把对应的Text组件拖到
currentTimeText字段完成赋值就行
可选逻辑优化
你当前的脚本还有两个计时逻辑的小问题,建议一并修复:
- 目前只取了
TimeSpan.Seconds赋值,这个值是0-59循环的秒数,超过1分钟就会归零重新计数,无法显示累计的总游戏时长 - 没有做空值保护,后续如果不小心误删Text组件、或者字段漏赋值,会直接抛错中断运行
修正后的完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class Stopwatch : MonoBehaviour { bool stopwatchActive = false; float currentTime; public Text currentTimeText; void Start() { currentTime = 0; StartStopwatch(); } void Update() { // 空值保护,避免空引用 if (currentTimeText == null) return; if (stopwatchActive) { currentTime += Time.deltaTime; } TimeSpan time = TimeSpan.FromSeconds(currentTime); // 格式化显示 时:分:秒,可根据需求自行调整格式 currentTimeText.text = time.ToString(@"hh\:mm\:ss"); } public void StartStopwatch() { stopwatchActive = true; } public void StopStopwatch() { stopwatchActive = false; } }
内容的提问来源于stack exchange,提问作者user19401177
相关产品推荐
相关产品推荐

