Is it possible to perform a TRUE null-check?

I’m aware of how ==null behaves in classes derived from UnityEngine.Object - no need to explain that. However it really stands in my way, because it seems I’m unable to perform true null-check. Like: I have no way to differentiate destroyed object from real null. Is there any way to find out, if a reference is really a null, not a destroyed object? Or do I have to do some workarounds?

Found it!

Apparently there is much, much simpler way to compare with true null. One property of == operator saved the day: it is not polymorphic. It means, that though every descendant of UnityEngine.Object gets this nasty surprise as a gift, there is one ancestor of UnityEngine.Object, which remembers good old ways: System.Object.

In other words:

bool a = destroyedObject == null;
bool b = (System.Object)destroyedObject == null;
bool c = (object)destroyedObject == null;

Variable a will be true, whereas b and c will be false, since destroyedObject is not a null reference. In fact c is just a simpler way to write b.

Unsurprisingly, calling Equals method even when object is cast to System.Object does not work - since Equals is polymorphic.

Actually I wrote myself an extension method just so I wouldn’t need to use cast all the time:

public static bool IsTrueNull(this UnityEngine.Object obj)
{
    return (object)obj == null;
}

Of course you can call extension method even on null references (so it works), since it isn’t a true member, just a syntactic sugar.

Here is another way to check for null : Object.ReferenceEquals

public GameObject myGameObj;    
if( Object.ReferenceEquals( myGameObj, null ) )
{
    Debug.Log("myGameObj is null");
}

It is slightly faster depending on the implementation.

Yes you can test if a reference is really null by simply casting it to “object”.

Example:

Transform someObjectReference;

if (someObjectReference == null)
{
    if ((object)someObjectReference == null)
    {
        // Really null
    }
    else
    {
        // Unity fake null
    }
}

I think an extension method like this should work as well:

public static class UnityObjectExtension
{
    public static bool IsRealNull(this UnityEngine.Object aObj)
    {
        return (object)aObj == null;
    }
}

With that you should be able to do this:

if (someObjectReference.IsRealNull())
{
}

Just use the static Object.ReferenceEquals() method

you can Either cast to System.Object, and then compare with == null, or you can use System.Object.ReferenceEquals(mythingie, null);

The cast to object is marginally faster.

What about obj is null? I guess this is it, no?

Actually, there are 3 ways to check for real null:


  1. bool isNull = !value && !(value is UnityEngine.Object);
  2. bool isNull = ((object)value) == null;
  3. bool isNull = ReferenceEquals(value, null);