Strange “Collection was modified after the enumerator was instantiated” exception

后端 未结 4 1533
不思量自难忘°
不思量自难忘° 2020-12-17 16:43

Perhaps someone can point me in the correct direction, because I\'m completely stumped on this.

I have a function that simply prints out a LinkedList of classes:

4条回答
  •  醉话见心
    2020-12-17 17:12

    I don't know if this is relevant to the OP but I had the same error and found this thread during a google search. I was able to solve it by adding a break after removing an element in the loop.

    foreach( Weapon activeWeapon in activeWeapons ){
    
                if (activeWeapon.position.Z < activeWeapon.range)
                {
                    activeWeapons.Remove(activeWeapon);
                    break; // Fixes error
                }
                else
                {
                    activeWeapon.position += activeWeapon.velocity;
                }
            }
        }
    

    If you leave out the break, you will get the error "InvalidOperationException: Collection was modified after the enumerator was instantiated."

提交回复
热议问题