- Home /
InvalidOperationException Collection was modified;
Getting this error here:
tList.Add(PlatformOBJChild);
foreach (Transform t in tList) // <-- Error here
{
if (t == null)
{ tList.Add(PlatformOBJChild);
}
}
is your tList initiated? the foreach loop goes through all (existing) elements in a list so why do you check if t is null?
What type is tList?
tList is a Transform list, and it is initiated. I think... It should be!
Answer by TonyLi · Jun 11, 2013 at 07:31 PM
You shouldn't modify the contents of collections while you're iterating on them.
You can use a temporary list to do this:
List<Transform> itemsToAdd = new List<Transform>();
foreach (Transform t in tList) {
if (t != null) {
foreach (Transform child in t) {
itemsToAdd.Add(child);
}
}
}
foreach (Transform item in itemsToAdd) {
tList.Add(item);
}
Note that the first foreach loop will only add children one level deep. You could use a recursive function (or something similar) to recursively add all children and their children.
Example of what I just explained... +1 for not being lazy like me.
FANTASTIC! That worked!
Now I just need it to stop giving the $$anonymous$$issing(Transform) in the inspector.
EDIT: Fixed! Unity you sexy bitch! if (tList.Contains(null)) { tList.Remove(null); }
Did not know you can check for a null in a list, remove it, and then it will automatically add the correct object.
Answer by tsmitro · Jun 11, 2013 at 07:28 PM
You are receiving that error because you are modifying your collection while iterating over it... that error is thrown on the second iteration because you have added another element. Read this if you want a more in depth explanation. Bottom line: do not add to, remove from or change values of any collection while you are looping through it.
Take his verbatim, he made it easy for you... this isn't related to Unity at all, it deals with Collections in the .NET Framework.
You mean! I'm not working in Unity! $$anonymous$$y whole life is a lie!
Thanks anyway :P.
Answer by florinel2102 · Dec 07, 2020 at 09:01 PM
If you wanna to delete an element (or more) just iterate with for/while and increment index only when the item is not deleted and pay attention to if you save count (n = exampleList.Count) in a variable to decrement when an element is deleted .
for(int i = 0; i<exampleList.Count;)
{
if(exampleList[i] == null)
{
exampleList.Remove(exampleList.[i]);
continue;
}
++i;
}