- Home /
GameObject member becomes null for no reason
I have a struct (could also be a class, doesn't change anything) which has a public GameObject member. This public member sometimes somehow gets null, completely on it's own. I also made the member private and wrote a getter, setter to check if somewhere it is set to null but that's not the case.
Also what's intereseting is, that printing this member with Debug.Log prints "Null" when I set it to null on my own and it prints "null" when it turns null automatically.
So this is the C# struct with getter and setter where I can check if the private member gameObject gets set to null, but that's not the case, it just turns null sometime on its own:
private struct Helper
{
private GameObject gameObject;
public GameObject GameObject
{
get { return this.gameObject; }
set { this.gameObject = value; }
}
}
Thanks for any help!
Answer by whydoidoit · Nov 24, 2012 at 02:32 PM
Unity automatically makes GameObject references (and all Components) turn null when ever you destroy the game object. You can't stop that from happening - so you'll have to work out where it gets destroyed.
It doesn't get destroyed and when it gets destroy your reference turns invalid, but not null.
No - they turn null. That's how Unity works.
If they are null, something has destroyed that object - like loading a level etc.
In fact it can be very annoying, because you get exactly the effect you are seeing. Unity makes anything that has Destroy called on it return null - in the same way as they made Unity object references castable to bool.
So you can do
if(someComponentReference) ...
But cannot do
if(someNormalClassReference) ...
See this thread where the Unity tech master explains the functionality.
Hm okay, then maybe something really gets destroyed.. thing is I still can see the GameObject inside the game. I'll see if it's a logical problem. Thanks for the help!