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.
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.