C# foreach循环内不要修改集合

为解决游戏中剧情脚本延时创建NPC的问题,作者分享了一段使用C#编写的代码,并介绍了从使用LinkedList及遍历删除到改进为List结合RemoveAll委托方法的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前在游戏中为了实现剧情脚本延时创建Npc的功能,写了这么一段代码:

LinkedList<CreateNpcTask> DelayCreateNpcTasks = new LinkedList<CreateNpcTask>();

        void TickDelayCreateNpc()
        {
            foreach (CreateNpcTask task in DelayCreateNpcTasks)
            {
                task.timer += UnityEngine.Time.deltaTime;
                if (task.timer * 1000 > task.delay)
                {
                    CreateNpcEntity(task.unitId);
                    DelayCreateNpcTasks.Remove(task);
                }
            }
        }

void AddCreateNpcTask(int unitId, float delay)
        {
            CreateNpcTask node = new CreateNpcTask();
            node.unitId = unitId;
            node.delay = delay;

            DelayCreateNpcTasks.AddLast(node);
        }

之后一直没充分测试,丢在那一个多月,今天被测出来报异常,然后被主程揪了出来。

改成了这样:

List<CreateNpcTask> DelayCreateNpcTasks = new List<CreateNpcTask>();

        void TickDelayCreateNpc()
        {
            DelayCreateNpcTasks.RemoveAll(delegate(CreateNpcTask task)
            {
                task.timer += UnityEngine.Time.deltaTime;
                if (task.timer * 1000 > task.delay)
                {
                    CreateNpcEntity(task.unitId);
                    return true;
                }
                return false;
            });            
        }

        void AddCreateNpcTask(int unitId, float delay)
        {
            CreateNpcTask node = new CreateNpcTask();
            node.unitId = unitId;
            node.delay = delay;

            DelayCreateNpcTasks.Add(node);
        }


《C#本质论》第14章有这么一小节:



基本的语法没事还是要多翻翻啊。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值