Difference between "Destroy" and "DestroyImmediate" ?

Hi,

ive just had a problem but i get it done - now its working. But to learn from that, i would like to know why that happend.

cube = GameObject.Find("cube");
if (cube ) print("destroy cube"); DestroyImmediate(cube);
print("cube here:" + cube.name);

If i dont use "DestroyImmediate", i always get a print-output, although it was destroyed. So my question: when does the Destroy and when the DestroyImmediate functions work?

From my understanding, they both always work. It's just that DestroyImmediate incurs the overhead of setting all the references to that game object or component to Unity's fake null immediately, whereas with Destroy it happens at the end of the frame.

According to the docs you're supposed to avoid using DestroyImmediate unless you absolutely need those references to be removed when that call happens. Otherwise just use Destroy and realize that until the next frame, that object is still there.

There's also some more information here: http://unity3d.com/support/documentation/ScriptReference/Object.DestroyImmediate.html

The docs Unity - Scripting API: Object.DestroyImmediate are clear on this:

This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead.

Using DestroyImmediate can really mess up the orderings of your OnDestroy calls, plus the docs just say you shouldn’t do it, so don’t.

If you’re destroying a reference to a gameobject, just null it afterwards for consistent behaviour:

cube = GameObject.Find("cube");
if (cube ) { 
    print("destroy cube"); 
    Destroy(cube);
    cube = null;
}
print("cube here:" + cube.name); // now it throws a null ref exception

One more time for the folks at the back: the docs say don’t use DestroyImmediate at runtime. Don’t use DestroyImmediate at runtime.

I find DestroyImmediate() only option when dealing with childs of transform (GameObject) when i check right away how many childs are left

Used for some HideFlags: Unity - Scripting API: HideFlags.

And is found in 5.5 post processing.

Destroy()

  • This just destroy the game object passed as parameter.

  • It set all the references to that game object to null at the end of frame.


DestroyImmediate()

  • As the name suggest it immediately destroy the gameobject passed as parameter.

  • It set all the references to that game object to null immediately, it will not wait for the frame to end like Destroy() function.