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

如何获取数组中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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 09:45:57