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?
CodePudding user response:
logging it returns
null
Yes, because UnityEngine.Object
has a custom implementation for ToString
.
The object basically still exists. Only the underlying c
object was "Destroyed" but your static
reference still holds a 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 has a custom implementation for ==
.
CodePudding user response:
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.