Check if a GameObject has been assigned in the inspector in Unity3D 2019.3.05f
Solution 1:
Unity has a custom implementation of equality ==
operator (see Custom == operator, should we keep it? which often leads to confusion / unexpected behavior.
Even if an UnityEngine.Object
has a value equal to null
it is sometimes not == null
.
Object
rather still stores some meta data in it e.g. you get a MissingReferenceException
, not a usual NullReferenceException
because Unity implemented some custom exceptions that often hold more detail to why the value is equal to null
.
Especially since
public GameObject testObject = null;
is a public
field it is automatically serialized and thus the null
value you assigned to it will be overwritten anyway during the serialization.
UnityEngine.Object
which GameObject
derives from has an implicit operator bool
Does the object exist?
Instead of a direct == null
comparison you should rather check for
public static bool IsNull<T>(this T myObject, string message = "") where T : UnityEngine.Object
{
if(!myObject)
{
Debug.LogError("The object is null! " + message);
return false;
}
return true;
}
For a general method working for any reference type you could e.g. use something like
public static bool IsNull<T>(this T myObject, string message = "") where T : class
{
if (myObject is UnityEngine.Object obj)
{
if (!obj)
{
Debug.LogError("The object is null! " + message);
return false;
}
}
else
{
if (myObject == null)
{
Debug.LogError("The object is null! " + message);
return false;
}
}
return true;
}