Lately I’ve been trying to contribute code to assorted Kerbal Space Program mods that I enjoy using. Per my Code Quality article, naturally I tried to apply those techniques to said code. However, there’s a lot of gnashing of teeth regarding null object handling in Unity apps & games.

Problem at hand#

Unity overrides == to do some alternative behavior. They create “fake null” objects and overloaded the operator to detect those. They also use C/C++ code as a backend to their C# libraries; and C/C++ can be unkind with null pointers and such. The developer said they’d revisit it in Unity 5… but that was a few years ago, and it seems like the behavior persists as late as 2021 (saw some discussion forum posts regarding their customized Mono runtime, and a slow progress to bring it to current .NET standards). Unity at least supports C# 7 as of 2019, which means C# 8-10 nullable reference type changes don’t apply here. IDEs may push you to use null operators like ?. and ??; the Microsoft Unity Analyzers can help find existing ones that apply to Unity objects and re-write those (the operators seem fine for non-Unity objects).

Fixes#

1. Microsoft’s linting rules on this…#

Old code

return transform?.transform;
return a ?? b;

New code

return transform != null ? transform : null;
return a != null ? a : b;

2. A Reddit user suggested this snippet of code to try.#

I had to re-work how to use it, but the method works.

Make an extension method on UnityEngine.Object like

public static Object IfValid(this Object obj)
{
    if (!obj) return null;
    return obj;
}

This seems to work with it. Maybe can use ?., but the Unity checker still flags it.

int health = enemy.IfValid() ? enemy.Health : 0;

References to look over#