Unity中无法读取Update内静态值的问题求解(附代码)
问题解决:Unity跨类获取累加数值的正确实现
方案1:全局共享计数(保留静态变量)
静态变量属于类而非实例,适合全局唯一的分数/计数场景,直接通过类名访问即可,无需引用对象实例。
修改后的Rock类
using TMPro; using UnityEngine; public class Rock : MonoBehaviour { [Header("Points")] public TextMeshProUGUI points; // 静态变量,全局所有Rock实例共享该值 public static int point; private void Start() { points = GetComponent<TextMeshProUGUI>(); // 初始化静态变量,避免场景切换后数值残留 point = 0; } void Update() { Move(); } void Move() { point += 1; Debug.Log(point); // 同步显示到UI(按需添加) if(points != null) points.text = point.ToString(); } }
修改后的Points类
using TMPro; using UnityEngine; public class Points : MonoBehaviour { [Header("Points")] public TextMeshProUGUI points; void Update() { // 直接通过类名访问静态变量 int currentPoint = Rock.point; Debug.Log("points: " + currentPoint); // 同步显示到UI(按需添加) if(points != null) points.text = currentPoint.ToString(); } }
方案2:独立实例计数(移除static)
如果需要每个Rock对象维护独立的计数,需确保Points类的countPoint引用正确赋值(在Unity Inspector面板拖入目标Rock对象)。
修改后的Rock类
using TMPro; using UnityEngine; public class Rock : MonoBehaviour { [Header("Points")] public TextMeshProUGUI points; // 实例变量,每个Rock对象拥有独立数值 public int point; private void Start() { points = GetComponent<TextMeshProUGUI>(); point = 0; } void Update() { Move(); } void Move() { point += 1; Debug.Log(point); if(points != null) points.text = point.ToString(); } }
修改后的Points类
using TMPro; using UnityEngine; public class Points : MonoBehaviour { [Header("Points")] public TextMeshProUGUI points; // 需在Inspector面板拖入目标Rock对象 public Rock countPoint; void Start() { // 检查引用是否正确赋值,避免空引用错误 if(countPoint == null) { Debug.LogError("请在Inspector面板为countPoint赋值Rock对象"); } } void Update() { if(countPoint == null) return; int currentPoint = countPoint.point; Debug.Log("points: " + currentPoint); if(points != null) points.text = currentPoint.ToString(); } }
关键注意事项
- 静态变量会在程序生命周期内保留数值,场景切换时需手动初始化重置
- 使用实例变量时,必须确保Inspector面板中的
countPoint引用正确,否则会读取到0或触发空引用错误
内容的提问来源于stack exchange,提问作者Skóra
相关产品推荐
相关产品推荐

