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

Unity中Instantiate()始终抛出NullReferenceException问题求助

解决Instantiate抛出NullReferenceException的问题

核心问题定位

你代码里的playerTeamUnitsGO和enemyTeamUnitsGO两个List<GameObject>变量仅做了声明,但没有初始化实例。当你尝试通过playerTeamUnitsGO[i] = Instantiate(...)给列表元素赋值时,由于列表本身是null,直接访问索引会触发NullReferenceException——这和Instantiate的参数无关,所以你之前检查参数是否为空的Debug无法定位到问题。

修复步骤

在使用这两个列表之前,先完成初始化,同时建议改用更安全的列表添加方式:

void SetupBattle() //should be called at the start of the battle
{
    Debug.Log("setup battle is called");
    // 初始化两个GameObject列表
    playerTeamUnitsGO = new List<GameObject>();
    enemyTeamUnitsGO = new List<GameObject>();

    for (int i = 0; i < allyTeamUnits.Count; i++)
    {
        Debug.Log(baseUnit == null);
        Debug.Log(playerPos == null);
        Debug.Log(Quaternion.identity == null);
        Debug.Log(canvas.transform == null);
        // 实例化后用Add方法加入列表,避免索引访问的空引用问题
        var newPlayerUnit = Instantiate(baseUnit, playerPos, Quaternion.identity, canvas.transform);
        newPlayerUnit.SetActive(true);
        newPlayerUnit.GetComponent<Unit>().Init(allyTeamUnits[i]);
        playerTeamUnitsGO.Add(newPlayerUnit);
    }
    Debug.Log("info initialized");

    // 修正敌人循环条件,避免索引越界
    for (int i = 0; i < enemyTeamUnits.Count && i < 3; i++)
    {
        var newEnemyUnit = Instantiate(baseUnit, enemyPos, Quaternion.identity, canvas.transform);
        newEnemyUnit.SetActive(true);
        newEnemyUnit.GetComponent<Unit>().Init(enemyTeamUnits[i]);
        enemyTeamUnitsGO.Add(newEnemyUnit);
    }
}

额外优化提示

原敌人循环的条件i < enemyTeamUnits.Count || i < 3存在逻辑错误,会导致当enemyTeamUnits数量不足3时,循环仍会执行到i=2,此时访问enemyTeamUnits[i]会触发索引越界异常,建议改用&&(逻辑与)来限制循环次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:01:14