I’m trying to remove items from a list of GameObjects, but whenever I try to it gives an error during the game, and doesn’t remove the item. The error message it gives is: InvalidOperationException: Collection was modified; enumeration operation may not execute. I’m not sure if it’s just a simple mistake because this is my first game coded in Unity, but I can’t figure out whats going on. The code is below (I excluded the unimportant stuff):
When removing items from a collection, you can either enumerate said collection backwards, or, build a list of items to remove as you run through the initial collection, then afterwards, run through the temporary list of items to remove, removing each one from the main list.
In code form:
int count = someList.Count;
for (int i = count - 1; i >= 0; i--)
{
var item = someList[i];
if (item // passes some condition)
{
someList.RemoveAt(i);
}
}
// OR
var toRemove = new List<SomeType>();
foreach (var item in someList)
{
if (item // passes some condition)
{
toRemove.Add(item);
}
}
foreach (var item in toRemove)
{
someList.Remove(item);
}
It is no longer giving an error message, but it does not appear to be deleting the items from the list? I used Debug.Log(); to get the list length, and the number only goes up, never down. I used spiney199’s first method. Honestly, I’m probably fine with this as it is, since I doubt the items would cause any lag, since they’re only black squares and the game is pretty short.