"enumeration operation may not execute" Problem with C# list

So I am making buttons with this code

` void gcListItem(Texture strItemName)

    if(GUILayout.Button((strItemName), GUILayout.Height(100))){




void gcListBox()


GUILayout.BeginArea (new Rect (40,230,400,300));
scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(250), GUILayout.Height(250));

foreach(Texture _texture in Buttons){



The problem is that when I click on the button I get this error :
[InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.List1+Enumerator[UnityEngine.Texture].VerifyState () System.Collections.Generic.List1+Enumerator[UnityEngine.Texture].MoveNext ()]

The code that causes this error is Buttons.Remove(strItemName);

The question is how do I fix it please Help.

This is a design feature of .NET list enumerators, you can’t modify the underlying object referenced by an enumerator. Foreach loops iterate through a list via enumerators, specifically the IEnumerator interface.

When using the List class, you can avoid this situation two ways…

  1. By iterating through the collection via array indexes, thereby avoiding enumeration entirely.

    for(int i=0; i<Buttons.Count; i++)
    Texture _texture = Buttons*;*
    2) By copying the collection and iterating through the copy.
    foreach(Texture _texture in Buttons.ToArray())
    This works because the Button list isn’t being enumerated in this case, the new array is, so you are free to modify the Button list any way you want. However, copying the Button list is obviously an expensive operation, you don’t want to use this technique if the list is large or if this code called very frequently.
    Hope that answers the question. :slight_smile: