So when you Destroy a game object… any and all references to it turn null. How exactly does Unity implement this functionality? Is it a built-in .Net feature that anyone can use, or is it just a reference registry in each game object somehow?
Bump.
It’s a special thing we implemented (and which is only turned on in the editor). When you Object.Destroy() a unity object, the managed wrapper (the .net object you usually interact with), is not thrown away. instead the managed wrapper realizes that the object it wraps is destroyed, and informs you of that fact when you try to do anything with it.
When you have no more references to the .net object, and a new garbage collector run happens, the actual wrapper object itself will be cleaned up.
Bye, Lucas
Added this to Unity Answers ![]()
Alrighty, so basically… every call you make on a gameobject or its components… starts with some kind of null reference check against the unmanaged object?
I just tested this but got the same behavior in the web player as in the editor.
I created two Spheres. One sphere had the following script:
function OnMouseDown() { Destroy(gameObject); }
The other sphere had this script:
var go : GameObject; // set this to the other sphere
var go : GameObject; // set to the other sphere
var doneOnce = false;
function Update() {
if (go == null !doneOnce) {
doneOnce = true;
GameLog.GetInstance().Info("go == null"); // my gui log
}
In both cases the “go” reference was set to null automatically when I clicked on the sphere that “go” referred to.
What’s the expected behavior from Unity? Is this a bug or a feature working as expected?
I also posted this on Unity Answers.
I’d imagine that’s the expected behavior, it’s a “smart pointer”.
I think so to. It certainly is handy and it is a good idea to keep behavior in the editor as consistent as possible with deployment behavior. I’d like to get confirmatiin from unity ![]()
Can we get the direct link please? I can’t find the answer.
Unity folk:
Does this behavior only happen in the Editor? Mobile/Console is my target.
You quoted a post from 12 years ago.
But, no, destroyed objects return true when comparing with null in builds also. Otherwise everything would be broken always.