You need to enable JavaScript to run this app. 如何修复Unity换用List后出现的枚举修改、索引越界报错?
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Unity换用List后出现的枚举修改、索引越界报错?

List替换后两类运行时报错的修复方案

报错触发根源

  • InvalidOperationException: Collection was modified; enumeration operation may not execute.:出在GoreanTurret脚本的Update方法中,直接在foreach遍历TargetsWithinRange集合的过程中执行Remove操作,C#的集合迭代器不允许在遍历过程中修改集合结构,一旦触发就会抛这个异常。
  • ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.:出在两个脚本的正序for循环删除List元素的逻辑中——之前尝试把foreach改成正序for没生效,就是因为正序遍历删除元素时,被删元素后续的所有元素索引会整体前移1位,循环变量自增后会直接跳过未检查的元素,甚至最终i值超过当前集合的实际长度,触发越界。

分脚本修复实现

POW_Camp 脚本

原代码除了循环越界问题,还存在每帧重复调用Destroy(Fences)的冗余逻辑,修复后代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class POW_Camp : MonoBehaviour
{
    public GameObject AmmunitionsDump;
    public GameObject Explosion;
    public GameObject Fences;
    public List<GameObject> Prisoners;
    private bool isCampUnlocked = false; // 避免重复触发解锁逻辑

    void Update()
    {
        var ammoHealth = AmmunitionsDump.GetComponent<Health>();
        if (ammoHealth.CurrentHealth <= 0)
        {
            AmmunitionsDump.SetActive(false);
            Explosion.SetActive(true);
        }

        // 仅在弹药被摧毁的首次触发时执行后续解锁逻辑
        if (!AmmunitionsDump.activeSelf && !isCampUnlocked)
        {
            isCampUnlocked = true;
            Destroy(Fences);
            
            // 倒序遍历集合删除空元素,从根源避免索引越界
            for (int i = Prisoners.Count - 1; i >= 0; i--)
            {
                var prisoner = Prisoners[i];
                if (prisoner == null)
                {
                    Prisoners.RemoveAt(i);
                    continue;
                }
                prisoner.GetComponent<PlayerData>().Captured = false;
            }
        }
    }
}

GoreanTurret 脚本

原代码除了两个循环逻辑报错,还存在每帧重复调用GetComponent、重复判断目标状态的冗余逻辑,修复时提前缓存组件、拆分逻辑模块,核心删除逻辑全部换成倒序遍历,修复后代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GoreanTurret : MonoBehaviour
{
    public GameObject Projectile;
    public GameObject FiringPoint;
    public GameObject GunTower;
    public GameObject HealthBar;
    public List<GameObject> TargetsWithinRange = new List<GameObject>();
    public float FiringRange = 100;
    public GameObject CurrentTarget;
    public bool TargetLocked;

    // 提前缓存组件,避免每帧重复GetComponent带来的性能损耗
    private Slider healthSlider;
    private Health turretHealthComp;

    void Start()
    {
        InvokeRepeating(nameof(Shoot), 1f, 0.5f);
        healthSlider = HealthBar.GetComponent<Slider>();
        turretHealthComp = GetComponent<Health>();
        healthSlider.maxValue = turretHealthComp.MaxHealth;
    }

    void Update()
    {
        healthSlider.value = turretHealthComp.CurrentHealth;
        FindTargetsWithinRange(FiringRange, TargetsWithinRange);
        CleanInvalidTargets();
        UpdateCurrentTarget();

        // 锁定目标时炮台转向
        if (TargetLocked && CurrentTarget != null)
        {
            GunTower.transform.LookAt(CurrentTarget.transform);
        }
    }

    // 独立清理无效目标,全程倒序遍历避免修改集合时触发异常
    void CleanInvalidTargets()
    {
        for (int i = TargetsWithinRange.Count - 1; i >= 0; i--)
        {
            var target = TargetsWithinRange[i];
            // 统一判断目标失效场景:空对象、未激活、无有效血量组件、血量为0、超出射程
            bool isInvalid = target == null
                             || !target.activeSelf
                             || target.GetComponent<Health>() == null
                             || target.GetComponent<Health>().CurrentHealth <= 0
                             || Vector3.Distance(transform.position, target.transform.position) > FiringRange;

            if (isInvalid)
            {
                // 若删除的是当前锁定目标,同步重置锁定状态
                if (target == CurrentTarget)
                {
                    CurrentTarget = null;
                    TargetLocked = false;
                }
                TargetsWithinRange.RemoveAt(i);
            }
        }
    }

    // 独立更新当前选中目标
    void UpdateCurrentTarget()
    {
        // 无有效锁定目标时,从剩余列表中选第一个可用目标
        if (!TargetLocked && CurrentTarget == null && TargetsWithinRange.Count > 0)
        {
            CurrentTarget = TargetsWithinRange[0];
            TargetLocked = true;
        }
    }

    void FindTargetsWithinRange(float range, List<GameObject> TargetList)
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, range);
        foreach (Collider collider in colliders)
        {
            var playerData = collider.gameObject.GetComponent<PlayerData>();
            // 仅加入未被俘获、未在现有目标列表中的对象
            if (playerData != null && !playerData.Captured && !TargetList.Contains(collider.gameObject))
            {
                TargetList.Add(collider.gameObject);
            }
        }
    }

    public void Shoot()
    {
        if (TargetLocked && CurrentTarget != null)
        {
            Instantiate(Projectile, FiringPoint.transform.position, FiringPoint.transform.rotation);
        }
    }
}

同类问题通用修复规则

  • 只要需要在遍历集合的过程中删除元素,绝对不要用foreach遍历要修改的目标集合,也不要用从0开始的正序for循环,统一采用倒序循环(从集合最后一个元素开始,索引从Count - 1递减到0),这种方式下删除当前索引的元素不会影响前面未遍历元素的索引位置,从根源规避迭代器异常和索引越界。
  • 遍历过程中执行Remove操作后,不要再访问原索引位置的元素,避免因集合长度变化触发空引用或越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 01:45:05