InvalidOperationException: Collection was modified; enumeration operation may not execute

Getting an InvalidOperationException here and it’s related to a foreach loop and other things in my Character script. In my initFormulas, I’m cycling through the list of values in statscontainer and checking if the base value has a formula attached to it hence the foreach loop with an if statement attached to it.

Please help me. Thank you.

A collection that you iterate over with foreach can not be modified during the execution of the loop.

Enumerators can be used to read the
data in the collection, but they
cannot be used to modify the
underlying collection. If changes are
made to the collection, such as
adding, modifying, or deleting
elements, the behavior of the
enumerator is undefined.

IEnumerable.GetEnumerator Method’s documentation

A simple solution for this case is to create a copy of the collection before starting the loop, but you need to evaluate if this is a good option for your case considering memory usage and performance.

foreach(ValueReference valueReference in statsContainer.valueList.ToArray())

.ToArray() is extension method available in System.Linq namespace.