UNT0023 Coalescing assignment on Unity objects

February 5, 2021 ยท View on GitHub

Unity overrides the null comparison operator for Unity objects, which is incompatible with coalescing assignment.

Examples of patterns that are flagged by this analyzer

using UnityEngine;

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

    public Transform NP()
    {
        return a ??= b;
    }
}

Solution

Use null comparison:

using UnityEngine;

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

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

A code fix is offered for this diagnostic to automatically apply this change.