liveBook · Manning

Null handling

As explained in High Performance Unity Game Development

A null check is a test that determines whether a reference or object represents no value or has been invalidated.

A null check tests whether a reference represents no value or an object has been invalidated. Unity overloads == null for GameObjects and other UnityEngine.Object types, checking whether the native object still exists even if its C# wrapper remains. C# null-conditional and null-coalescing syntax may only check the managed reference. Repeating checks in hot loops can be costly: one test slowed a method by nearly 30% on Android. section 11.3

Reduce repeated checks without ignoring object lifetime:

  • Check editor-assigned references during loading rather than gameplay; use editor-only checks to catch missing assets during development. section 11.3.1
  • For dynamically downloaded assets, record when an object is valid so you do not repeatedly test it. section 11.3.1
  • Own creation and destruction, and avoid unmanaged coroutines, callbacks, or static subscriptions that can outlive their target. section 11.3.3 section 11.3.4
Listing 11.8 GameObject null check test
static void setGameObjectPos(Vector3 pos, GameObject go)
{
    go.transform.localPosition = pos;
}
 
static void setGameObjectPosNullCheck(Vector3 pos, GameObject go)
{
    if (go != null)
    {
        go.transform.localPosition = pos;
    }
}

Contrasts setting a GameObject's position directly with performing a null check first. section 11.3

How High Performance Unity Game Development covers it

How deep it goes
Compares checked and unchecked GameObject access, reports an Android slowdown, and gives strategies for limiting checks.
Examples
Uses GameObject position-setting methods, editor-assigned assets, and stars destroyed while a tween is still running.
What it assumes
Assumes familiarity with Unity GameObjects and MonoBehaviours; explains their overloaded null comparison.
What you can do after
Apply lifetime ownership and check-once strategies to reduce repeated Unity-object checks during gameplay.
How it connects
Connects null checks to branching, object lifetimes, coroutines, async callbacks, and static event subscriptions.

Also explained in

Compare how 3 books explain null handling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.