Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Strange behaviour with ?. operator

Discussion in 'Scripting' started by vikram-apilla-nd, Mar 29, 2023.

  1. vikram-apilla-nd

    vikram-apilla-nd

    Joined:
    Feb 25, 2022
    Posts:
    4
    Hey there!

    I came across a strange behaviour related to the null conditional operator when a reference is not assigned.

    When I have a nullable GameObject? as in the below code, and I try to access it via the null-conditional operator ?., there is an UnassignedReferenceException. This also applies when I replace GameObject? with the Rigidbody? type.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class NullBehaviourTest : MonoBehaviour {
    4.     public GameObject? obj;
    5.  
    6.     private void Start() {
    7.         obj?.SetActive(false);
    8.     }
    9. }
    However, when I have other nullable types such as Image? or my own Monobehaviour script, there don't seem to be any exceptions caused by the ?. operator. I used the code below to test that.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class NullBehaviourTest : MonoBehaviour {
    5.     public Image? obj;
    6.  
    7.     private void Start() {
    8.         obj?.gameObject.SetActive(false);
    9.     }
    10. }
    My question is - why does it cause an exception for types like GameObject or Rigidbody while no exceptions for types like custom Monobehaviour or Image?

    Is the ?. operator not fully supported for C# in Unity? Is there a current plan or roadmap related to nullable support for C# in Unity?

    Would love to get a take on this from Unity Devs.
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,883
    No it's not supported, and no it won't be supported because you can't override the operator(s).

    You shouldn't use these operators with Unity objects, as they override the
    ==
    and
    !=
    operators, which the non-overridable operators circumvent (which you generally don't want).
     
  3. FrankvHoof

    FrankvHoof

    Joined:
    Nov 3, 2014
    Posts:
    258
    It's fully supported for C#. Just not for Unity-Objects. That's because Unity uses both C# and C++-Objects (where the C#-Object is usually just a wrapper for the C++-Object). It also uses a 'fake NULL'-object on the C#-side (e.g. when using Destroy() it will set the C#-side to the fake NULL until the underlying C++-Object has its memory-location freed.