During the execution of the application, I fill in a List <object> _myList with the objects I need, using Couroutine .

In Update I _myList through my _myList list using the .First() extension method.

But while InvalidOperationException: Operation is not valid due to the current state of the object through the list, I get an exception: InvalidOperationException: Operation is not valid due to the current state of the object

Before iterating through the list, I check for null .

What is the reason for the exception being thrown?

    2 answers 2

    Busting a collection can result in an InvalidOperationException if during collection the collection is changed.

    • And how to avoid it? Without lock . - vmp1r3
    • @rdorn stupid advice - ToList() will ToList() with exactly the same error - Pavel Mayorov
    • exactly, something stupid, sorry. - rdorn
    • I made an event for synchronization and used .ToList() , it helped. But at the same time, the request in Update() crashes to this LINQ: element = myList.First(x => Vector3.Distance(x.gameObject.transform.position, gameObject.transform.position) <= radius); - vmp1r3

    I want to remind you that corutines and update are executed in the same thread. This is me to the fact that you mentioned about lock. Make sure that the collection contains exactly the elements that satisfy the predicate, and better replace First with FirstOrDefault and then check for null.