Remove Missing Objects from List

I have a list that is being monitored for it’s length:

var item_black : List.<GameObject>;

Some of the items placed in that list, sometimes get destroyed by the game, and I end up with a bunch of missing entries. One easy way I thought of clearing this is:

function FixedUpdate () {
	for (var sweetie : GameObject in item_black) if (sweetie == null) item_black.Remove(sweetie);

This actually works, but Unity throws an error:

InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.List`1+Enumerator[UnityEngine.GameObject].VerifyState () (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:778)
System.Collections.Generic.List`1+Enumerator[UnityEngine.GameObject].MoveNext () (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:784)
item_toucher.FixedUpdate () (at Assets/my_script.js:55)

Whats the safest way of doing this? Do I need to remove the game objects explicitly back to this script as and when they are removed, or is there a way to do a RemoveAll(null list) or RemoveAt(null list) in UnityScript?

You can’t use a foreach loop to modify the contents of what you’re enumerating (see [this video][1] for all the syntatic sugars behind foreach)

I would use LINQ for that:

myList = myList.Where(item => item != null).ToList();

I think the syntax for JS is:

myList = myList.Where(function(item) { return item != null }).ToList();

Another way to do it, is to iterate on your list backwards with a for loop, not foreach

for(var i = list.Count - 1; i > -1; i--)
   if (list *== null)*

[1]: C# IEnumerator - YouTube

listItems.RemoveAll(item => item == null);

So if you have a GameObject list:

gos.RemoveAll(GameObject => GameObject == null);

WOW, iterate on your list backwards with a for loop, not foreach

That solved my very big headache. Thank you.