缺少引用异常Unity C#

缺少引用异常Unity C#,c#,list,unity3d,C#,List,Unity3d,我在Unity游戏中遇到了一个问题,我的敌人列表中,如果一个组为空,它仍将运行for循环,导致引用“enemyGroupList[I][j].enabled=true;”的引用异常丢失行中的错误,并且未生成新组。我认为它没有删除空列表,但我似乎不明白为什么它没有 当我使用for循环时,我以前没有这个问题 for(int j = enemyGroupList.Count - 1; i>=0; i--) 这是抛出一个参数超出范围的异常,这不是我需要的,但它会正确更新组,并在需要时生成一个新的

我在Unity游戏中遇到了一个问题,我的敌人列表中,如果一个组为空,它仍将运行for循环,导致引用“enemyGroupList[I][j].enabled=true;”的引用异常丢失行中的错误,并且未生成新组。我认为它没有删除空列表,但我似乎不明白为什么它没有

当我使用for循环时,我以前没有这个问题

for(int j = enemyGroupList.Count - 1; i>=0; i--)
这是抛出一个参数超出范围的异常,这不是我需要的,但它会正确更新组,并在需要时生成一个新的组

void Update () {
    if(enemyGroupList.Count < groupNumber)
    {
        enemyGroupList.Add(createGroup());
    }

    // for each list in the group list
    for(int i = enemyGroupList.Count - 1; i >= 0; i--)
    {
        // for each opject in a given list
        for (int j = enemyGroupList[i].Count - 1; j >= 0; j--)
        {

            // pause and unpause enemies when the player pauses the game or is talking
            if (player.CurrState == PlayerScript.State.Paused || player.CurrState == PlayerScript.State.Talking)
            {
                enemyGroupList[i][j].enabled = false;
            }
            else
            {
                enemyGroupList[i][j].enabled = true;
            }

            // remove dead enemies
            if (enemyGroupList[i][j].Dead)
            {
                enemyGroupList[i].RemoveAt(j);
                // break avoids out of range exceptions
            }
        }
        if (enemyGroupList[i].Count == 0 || player.CurrState == PlayerScript.State.Win)
        {
            enemyGroupList.RemoveAt(i);
        }
    }
}
void更新(){
if(enemyGroupList.Count=0;i--)
{
//对于给定列表中的每个对象
对于(int j=enemyGroupList[i]。计数-1;j>=0;j--)
{
//当玩家暂停游戏或说话时,暂停并解除对敌人的暂停
如果(player.CurrState==PlayerScript.State.Paused | | player.CurrState==PlayerScript.State.Talking)
{
enemyGroupList[i][j]。enabled=false;
}
其他的
{
enemyGroupList[i][j].enabled=true;
}
//清除死去的敌人
if(enemyGroupList[i][j].Dead)
{
enemyGroupList[i].RemoveAt(j);
//中断可避免超出范围的异常
}
}
if(enemyGroupList[i].Count==0 | | player.CurrState==PlayerScript.State.Win)
{
enemyGroupList.RemoveAt(i);
}
}
}

谢谢

两个问题。您在哪里实例化
enemyGroupList
enemyGroupList
是这个类中的一个静态变量吗(它似乎是继承了
monobhavior
的某个类)?这只是更新方法。我将其实例化为更新方法之外的全局列表。是的,这个类继承自MonoBehaviorBut,但它是静态的吗?您是否将此
monobhavior
附加到多个
GameObject
?这将是一种可能性,因为您的
反向循环
看起来很好。它不是静态的,行为只附加到一个对象上。我可以通过给敌人对象一个销毁功能,并让敌人管理者在将敌人从列表中移除时调用该功能来修复它。