Problem with DestroyImmediate

Hi,
I’m using the following editor script:

@CustomEditor (CubeLine)
class CubeLineEditor extends Editor {
    function OnInspectorGUI () {
        if (GUI.changed)
            EditorUtility.SetDirty (target);
            if(GUILayout.Button ("Generate Boxes")) {
			target.GenerateCubes();
			}
			if(GUILayout.Button ("Destroy Boxes")) {
			target.KillChildren();
			}
            
        DrawDefaultInspector();	
       
    }
}

Referencing the KillChildren() function on another script:

function KillChildren () {
for(var child : Transform in transform){
	DestroyImmediate(child.gameObject);
	}
}

So I have a button which when pushed instantiates a load of cubes, and a button which is supposed to destroy them all. However, the destroy button takes a few presses to actually destroy all the instantiated clones.
When it’s 10 boxes to destroy, it takes four clicks.
When 30, five clicks.
When 100, seven clicks. And so on.
Why doesn’t the code successfully loop through all the children and destroy them all in one click/one run of the function?
Thanks
S

Is it killing some of the boxes per click or none of them until the 4th-7th click?

Yes, some boxes per click. And actually they seem to be destroyed in similar patterns each time depending on number/line length etc.
Very bizarre…

I’ve run into a version of this problem before. When you call DestroyImmediate it instantly kills the GameObject, and it messes up the iterator for the foreach loop.

EDIT:
I’m not 100% sure about the typing for JS, but here is my best shot at a quick fix.

function KillChildren () {
    var objsToDestroy : GameObject[] = new GameObject[transform.childCount];
    var idx : int = 0;
    for(var child : Transform in transform)
    {
        objsToDestroy[idx++] = child.gameObject;
    }
    for (var i : int = 0; i < objsToDestroy.Length; ++i)
    {
        DestroyImmediate(objsToDestroy[i]);
    }
}
1 Like

Amazing, that works. Thank you so much for your help!