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

Unity中获取指定标签GameObject的组件列表时触发NullReferenceException的问题求助

解决Unity中NullReferenceException的问题

嘿,我一眼就揪出了你的代码里的核心问题——你没有初始化fightersScripts列表!

问题根源

你只是声明了private List<FighterControl> fightersScripts;,但从来没有创建这个List的实例对象。当你在InitializeFighters方法里调用fightersScripts.Add(...)时,这个变量还处于null状态,自然会触发NullReferenceException。

另外,虽然你确认了所有对象都挂载了对应脚本,但为了代码更健壮,我们也可以加个防御性检查,避免万一出现意外情况导致的异常。

修正后的代码

// 直接在声明时初始化列表,或者在Start方法里初始化都可行
private List<FighterControl> fightersScripts = new List<FighterControl>();

private void Start()
{
    InitializeFighters();
}

private void InitializeFighters()
{
    GameObject[] tempfightersGM = GameObject.FindGameObjectsWithTag("Fighter");
    
    // 先判断是否找到目标对象,避免空数组遍历
    if(tempfightersGM.Length == 0)
    {
        Debug.LogWarning("场景中没有找到标签为Fighter的对象!");
        return;
    }

    foreach (GameObject fighterObj in tempfightersGM)
    {
        FighterControl fighterScript = fighterObj.GetComponent<FighterControl>();
        // 确保找到脚本再添加,避免空元素或异常
        if (fighterScript != null)
        {
            fightersScripts.Add(fighterScript);
        }
        else
        {
            Debug.LogWarning($"标签为Fighter的对象{fighterObj.name}未挂载FighterControl脚本!");
        }
    }
}

额外小建议

  • 使用foreach遍历数组/集合比for循环更简洁易读,适合这类不需要索引操作的场景
  • 加入日志提示能帮你更快定位问题,比如找不到对象或脚本时能及时看到反馈

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:02:34