之前在游戏中为了实现剧情脚本延时创建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章有这么一小节:
基本的语法没事还是要多翻翻啊。
为解决游戏中剧情脚本延时创建NPC的问题,作者分享了一段使用C#编写的代码,并介绍了从使用LinkedList及遍历删除到改进为List结合RemoveAll委托方法的过程。
2218

被折叠的 条评论
为什么被折叠?



