First, lets say you have a gameObject (go) and you want to do an if check on it. Is there a difference between these two checks?
if (go != null {}
or
if (go) {}
Lastly, how does the last one work? How is it returning a Boolean?
Thanks!
First, lets say you have a gameObject (go) and you want to do an if check on it. Is there a difference between these two checks?
if (go != null {}
or
if (go) {}
Lastly, how does the last one work? How is it returning a Boolean?
Thanks!
They’re equivalent. I personally always use the first (more explicit) option, as I find it’s more clear, but it depends on your background.
As for how it’s evaluating as a boolean, I believe a class can implement the “operator bool” override, such that an instance of the class can be evaluated in bool contexts. The following is taken from this link: https://github.com/jamesjlinden/unity-decompiled/blob/master/UnityEngine/UnityEngine/Object.cs
public static implicit operator bool(Object exists)
{
return !Object.CompareBaseObjects(exists, (Object) null);
}
You can see more info on that here:
Also note that when you check if a GameObject is null, Unity’s doing some extra magic behind the scenes to actually check if it’s either null or Destroyed. When you Destroy() a GameObject, it doesn’t instantly set all references to the object to null, but it would be bad if you acted on the Destroyed object. Anyway, checking if the object is null is the right approach in pretty much all cases, even if the object is destroyed.