如何获取数组中GameObject挂载脚本内的变量值?
解决Unity中获取数组内GameObject脚本变量的空引用异常
你的代码抛出NullReferenceException,大概率是以下两种情况之一:
exampleGo数组里存在未赋值的空元素(比如Inspector里漏填或者对象被误删)- 数组中某个GameObject没有挂载
ExampleScript脚本
给你修正后的代码,加入空值检查,既能避免崩溃,还能帮你定位问题:
public GameObject[] exampleGo; // 在Inspector中手动添加所有GameObject private void Start() { foreach (GameObject go in exampleGo) { // 先检查当前GameObject是否为空 if (go == null) { Debug.LogError("数组中存在空的GameObject元素"); continue; } // 获取组件并检查是否存在 ExampleScript exampleScript = go.GetComponent<ExampleScript>(); if (exampleScript == null) { Debug.LogError($"GameObject {go.name} 上未挂载ExampleScript脚本"); continue; } // 安全访问变量 Debug.Log($"{go.name} 的exampleInt值为: {exampleScript.exampleInt}"); } }
额外排查建议:
- 打开Inspector确认
exampleGo数组里的每个元素都正确关联了GameObject,没有空槽位 - 逐个选中数组里的GameObject,检查Inspector面板是否确实挂载了
ExampleScript - 如果
exampleInt是在ExampleScript的Start或Awake中初始化的,确保该脚本的执行顺序在当前脚本之前(可以在ProjectSettings -> Script Execution Order里调整)
内容的提问来源于stack exchange,提问作者Karl Sköld
相关产品推荐
相关产品推荐

