For Each Loops and List Set Item .Net3 vs .Net4

DarrenR 2 years ago updated 2 years ago 2


I've just updated to .Net4 Bolt (+Unity .net4 2018.4.6f1) and I have an error that didn't occur in .Net3 Bolt.

"InvalidOperationException: Collection was modified; enumeration operation may not execute."

I am using a For Each Loop node to iterate through a List<Vector4>. And inside the loop I am changing the Values of the Vector4's using the "List Set item" node. I am NOT adding or deleting anything from the list.

From what I can tell this shouldn't cause this error as I'm not changing the index of the list just the values. Why is this erroring with .Net4 but not with .Net3?

(I tried googling but found that all the posted errors came from adding or deleting from the list in the foreach loop which would obviously break)


Bolt Version:
Unity Version:
Scripting Backend:
.NET Version (API Compatibility Level):
Satisfaction mark by DarrenR 2 years ago

Hi Darren,

I'm surprised this worked in .NET 3, modifying a list (even setting items) is not supported in a ForEach.

I just did a quick fiddle to confirm: https://dotnetfiddle.net/oFJ7UJ

You could use a For Loop instead with the upper limit set to the list's count. This will let you modify items without a problem. Example fiddle converted to that approach: https://dotnetfiddle.net/5PC6O2

Yeah it's weird that it works in .net3

I did the For Loop thing instead and will make sure I don't use foreach when changing values in a collection from now on. 

Still loving Bolt! I'm doing a lot more coding now but Bolt is still super useful for me.