Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity: the null-coalescing operators not working

Problem

I cannot use ?? and ??= operators in Unity.

public class Compo : MonoBehaviour
{
    [SerializeField] Transform? _tr;

    void Start()
    {
        _tr ??= transform;
        Debug.Log(_tr);
    }
}

I attached this class to an object.

I did not attach any Transform to _tr property but the object’s transform should be assigned to _tr.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Eventually, I got null in the console.

Attempt

I tried not to use the operators like below.

if (_tr == null)
{
    _tr = transform;
}

Successfully, transform was assigned to _tr.

Then, I tried simpler code like below.

int? x = null;
x ??= 10;

I got 10.

Environment

  • OS: macOS 13.3.1 (a)(22E772610a)
  • Unity: 2021.3.22f1
  • Mono: 6.12.0.182
  • C#: .NET Standard 2.1

Additional Compiler Arguments

  • -nullable:enable

>Solution :

The null-coalescing and null-conditional (?. and ?[]) operators compare the reference of the left operand to null.

_tr ??= transform;

is equivalent to

if(object.ReferenceEquals(_tr, null))
    _tr = transform;

But all the Unity objects override the == operator so that even the references are not null, the objects can be equal to null. For example:

var r = GetComponent<Renderer>(); // suppose there is a renderer component attached
Destroy(r);
print(r == null); // true
print(object.ReferenceEquals(r, null)); // false

That’s why you should avoid to use these on Unity objects.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading