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.
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.