- Home /
The question is answered, right answer was accepted
Using DestroyImmediate on Arrays?
The docs say this about destroying objects in an array using DestroyImmediate:
"Also note that you should never iterate through arrays and destroy the elements you are iterating over. This will cause serious problems..."
Surely they mean a dynamic array? What's the problem with doing it on a static array? I understand on a dynamically allocated array that the contents may be shuffled/removed, but I thought it was safe on a static array.
I'm writing an editor script (C#) for which I need to Instantiate clones of a GameObject and store them in this static array:
private GameObject[] cloneSteps = new GameObject[12];
Further on I need to destroy them before re-instantiating them, so I do iterate over them:
if(cloneSteps != null){
for(int i=0; i<12; i++)
{
if( cloneSteps[i] != null)
DestroyImmediate(cloneSteps[i]);
}
}
I have been getting an intermittent bug, so I'm wondering if this is faulty? How else can you destroy/remove/delete objects in an array?
Am I right in thinking that there will be a memory leak if I simply overwrite the array before destroying the elements?
Thanks
Steve
Iterate through them backwards. Perhaps this example can give you a start, since I'm not sure exactly what you'll need. The For loop is the most important part here.
public void ClearChildren(GameObject parent)
{
List<Transform> children = new List<Transform>;
foreach(Transform child in parent.transform)
{
children.Add(child);
}
for(int i = children.Count - 1; i >= 0; i--)
{
Destroy(children[i].gameObject);
}
}
I updated the method to be a little more generic.
Yeah it's odd and sometimes still confuses me, but from my research, this happens to be the answer. I use this exact method quite frequently.
Answer by robertbu · Nov 12, 2013 at 05:08 PM
Unity uses a heap with garbage collection as the memory model.
Am I right in thinking that there will be a memory leak if I simply overwrite the array before destroying the elements?
No. You can simply overwrite the reference to some object. Assuming there are no other reference to it, the memory will be reclaimed the next time the memory manager. A couple of links:
http://docs.unity3d.com/Documentation/Manual/UnderstandingAutomaticMemoryManagement.html
http://answers.unity3d.com/questions/7853/garbage-collection.html
Thanks for the links. Would upvote but don't have enough rep.