USP0002 Unity objects should not use null propagation

March 2, 2022 ยท View on GitHub

UnityEngine.Object should not be used with null propagation.

Suppressed Diagnostic ID

IDE0031 - Null check can be simplified

Examples of code that produces a suppressed diagnostic

using UnityEngine;

class Camera : MonoBehaviour
{
	public Transform NP()
	{
		return transform != null ? transform : null;
	}
}

Why is the diagnostic reported?

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

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. Null propagation cannot be overridden in this way, and therefore behaves inconsistently with the == operator, because it checks for null in a different way.