USP0001 Unity objects should not use null coalescing

March 2, 2022 ยท View on GitHub

UnityEngine.Object should not be used with the null coalescing operator.

Suppressed Diagnostic ID

IDE0029 - Null check can be simplified

Examples of code that produces a suppressed diagnostic

using UnityEngine;

class Camera : MonoBehaviour
{
	public Transform a;
	public Transform b;

	public Transform NC()
	{
		return a != null ? a : b;
	}
}

Why is the diagnostic reported?

Under normal circumstances, return a != null ? a : b can be simplified to return a ?? b.

Why do we suppress this diagnostic?

Unity has overridden the == operator for UnityEngine.Object. If you use the == operator to compare a UnityEngine.Object to null, it will return true if the UnityEngine.Object is destroyed, even if the object itself isn't actually null. The ?? operator cannot be overridden in this way, and therefore behaves inconsistently with the == operator, because it checks for null in a different way.