分享

【Unity3D 问题总结】Unity报错提示:InvalidOperationException: Collection was modified; enumeration operation ma

 敲代码的小Y 2021-12-01

前言

在Unity中运行场景时报错,报错内容如下

在这里插入图片描述
原因是在foreach中不能修改处理的集合,Foreach体内运用了对Collection的Remove方法(或者Add方法)

比如下面这种

foreach (string item in StudentList)
        {
            items.Add(item);//不可操作
            items.Remove(item);//不可操作
        }

解决办法

如果遍历时涉及增删操作,则使用for循环

上面的例子改为:

     for (int j=0;j< StudentList.Count;j++)
            {
                StudentList.Add("");
                StudentList.Remove("");
            }

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多