• Tag Archives programming
  • Gotcha when testing Unity Objects for null in C#

    Unity has overloaded the ‘==’ operator, specifically, checking objects against “null” might not always do what you expect. More information can be found in this blog post from Unity.

    Specifically, if a Unity Object (as opposed to a C# object) gets destroyed, it will be set to a “fake null” object.  In this case, the following statements are true:

    1
    2
    3
    4
    
        obj == null          // true    obj is null          // false
        (object)obj == null  // false
        obj ?? value         // obj

    Note the different results between lines 1 and  2 & 3.

    If obj truly is null, then the results are as expected:

    1
    2
    3
    4
    
        obj == null          // true
        obj is null          // true
        (object)obj == null  // true
        obj ?? value         // value

    It may be more readable to provide an Extension Method to UnityObject:

        /// <summary>
        /// Extension Method on Unity Objects returning whether the object really is null.
        /// </summary>
        /// Unity overloads the '==' operator so that it returns true on both null references
        /// as well as references to destroyed objects. This function only returns true if
        /// the reference truly is null, and returns false for "fake null" objects.
        public static bool IsTrueNull(this UnityEngine.Object ob)
        {
            return (object)ob == null;
        }