Object references always get null when object is destroyed?

From my experiences, Unity do some magic when an object (not only gameobjects) is destroyed: Each and every reference to this object is automatically nullified, even inside generic lists and arrays.

This is great, but can I take this as true always? The problem is that I did read once ago that this happens only inside editor… but I do see this happens even on webplayer, standalone windows .exe and android.

Thanks!

Most of the objects in Unity are handled by the native part of the Unity Engine (written in C++). The C#/Mono classes which you use in the Editor are mostly wrappers around the stuff which is done in C++.

C#/Mono classes do not have a destructor (like C++), so you can not “destroy” an object in .NET/Mono languages, you can only remove all references to it and wait for the garbage collection to collect it. However, since most of Unity is done in C++, when you destroy an component (or an object), this is done in C++ part of the Engine and it frees the memory of the object in question, which invalidates all references to it.

If you don’t want to completely free up a component (or gameobject) form memory, don’t use “Destroy(mycomponent)” or “Destroy(gameObject)”. This do not works always of course, i.e. if you have an AI script that has another gameobject/transform as target, then you always have to check against null

// do early exit, if target do not reference to a valid object
if(target==null) 
   return;