Wiseak
Wiseak

Reputation: 13

What happend to a static variable that refer a gameobject when load another scene?

I have met a problem, a static varible is refering a gameobject in a scene. When I load another scene,the static variable will be null, but the space the gameobject take up will still remain in memory,and GC dont deal with it. Why is this?

Upvotes: 1

Views: 343

Answers (2)

derHugo
derHugo

Reputation: 90630

logging it returns null

Yes, because UnityEngine.Object has a custom implementation for ToString which returns "null" if the underlying object has been destroyed/unloaded.

The c# object instance basically still exists. Only the underlying c++ engine object was "Destroyed" / unloaded but your static reference still holds a c# GameObject, just an invalid one. Since it is static the GC doesn't collect it.

If you try to access it you will see you don't get a typical expected NullReferenceException but rather a custom MissingReferenceException which is only possible since the object still exists but Unity also has a custom implementation for == which returns true for someDestroyedObject == null since again it checks for the existence of the underlying c++ instance.

Upvotes: 2

Chuck
Chuck

Reputation: 2102

I thought garbage collection didn't collect until there were no references to the object, but your static variable is still holding the reference. It doesn't exist anymore, so it's null, but I don't think GC will collect until your static variable stops referring to it.

Upvotes: 0

Related Questions