USP0017 Unity objects should not use coalescing assignment

March 2, 2022 ยท View on GitHub

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

Suppressed Diagnostic ID

IDE0074 - Use compound assignment

Examples of code that produces a suppressed diagnostic

using UnityEngine;

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

    public Transform NC()
    {
        // Please note that this construct should not be used with Unity objects either, and will trigger a diagnostic.
        // We are just using it here for demonstration purposes.
        return a ?? (a = b);
    }
}

Why is the diagnostic reported?

Under normal circumstances, return a ?? (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 with those objects, it will not behave as expected because it checks for null in a different way.