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

So I am making buttons with this code

` void gcListItem(Texture strItemName)
{

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

Debug.Log(strItemName.name);
Buttons.Remove(strItemName);

}

    GUILayout.EndHorizontal();
}

void gcListBox()
{





    GUILayout.BeginVertical(GUI.skin.GetStyle("Box"));

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

foreach(Texture _texture in Buttons){

gcListItem(_texture);

}`

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*;*
    gcListItem(_texture);
    }
    …OR…
    2) By copying the collection and iterating through the copy.
    foreach(Texture _texture in Buttons.ToArray())
    {
    gcListItem(_texture);
    }
    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: