1.InvalidOperationException: out of sync
问题描述:
今天运行Unity遇到如下错误:
InvalidOperationException: out of sync
System.Collections.Generic.Dictionary`2+Enumerator[System.String,System.Boolean].VerifyState ()…
这里是我的源代码:
foreach(KeyValuePair<string,bool> keyValue in Content.GetComponent<HandleContent>().UserChoiceDic)
{
if(keyValue.Value == true)
{
Destroy(GameObject.Find(keyValue.Key));
Content.GetComponent<HandleContent>().UserChoiceDic.Remove(keyValue.Key);
}
}
原因如下:
foreach在迭代的时候,不能在迭代中删除正在迭代的集合,the program has no idea if it’s getting out of sync and could end up for instance in an infinite loop.事实上,即使是修改集合中的值也是不允许的。
错法一:
foreach(var i in someList)
{
someList.Add(i+5);
}
这样可能会导致重

在Unity中遇到InvalidOperationException: out of sync错误。此错误源于在foreach循环中尝试修改迭代的Dictionary。禁止在迭代过程中删除或修改集合以避免同步问题。解决方案包括使用List暂存键值对或引入LINQ进行操作。参考Unity社区解答。
——Encountered Problems&spm=1001.2101.3001.5002&articleId=84060903&d=1&t=3&u=721230aaada24cbdb8bc2867318714ee)
9694

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



