0

I have a script that listens for a couple of events and toggles the player UI accordingly. It is possible that the script might try to turn the UI back on, but it will be destroyed by another event in the meantime, that's why I have a null check whenever I disable or enable the UI. The problem is that when I use the null-propagation operator it still throws a null reference exception.

private void OnPlayerRotationStart()
{
    ToggleUI(false);
}

private void OnPlayerRotationStop(Quaternion newAngle)
{
    ToggleUI(true);
}

private void OnSuccessfulAttack()
{
    ToggleUI(false);

    Destroy(UI);
    Destroy(this);
}  

private void ToggleUI(bool state)
{
    // This works fine
    if (UI != null)
    {
        UI.SetActive(state);
    }

    // This throws null reference exception
    UI?.SetActive(state);
}

When I search for examples on the internet, people usually compare these two methods to be equal, yet my script thinks otherwise. Could someone explain why?

Hakej
  • 414
  • 4
  • 8
  • What type/scope is `UI`? – Uwe Keim Apr 21 '21 at 11:55
  • @UweKeim it's a GameObject, although different than the one containing the script I've mentioned, so it would still work when UI is not active. – Hakej Apr 21 '21 at 11:56
  • 4
    Probably related/duplicate of: [How am I misusing the null-coalescing operator? Is this evaluating “null” correctly?](https://stackoverflow.com/questions/56875706/how-am-i-misusing-the-null-coalescing-operator-is-this-evaluating-null-correc) or [UnassignedReferenceException even though using the null-conditional operator](https://stackoverflow.com/questions/60189192/check-if-a-gameobject-has-been-assigned-in-the-inspector-in-unity3d-2019-3-05f) or https://stackoverflow.com/questions/50103201/unassignedreferenceexception-even-though-using-the-null-conditional-operator – derHugo Apr 21 '21 at 11:56
  • @TimSchmelter I doubt if it's a threading issue, because if it would be, both methods should fail the same, yet one doesn't. I think it has something to do with the way "Destroy()" works in Unity, i.e. in the C# context object is not really null, but in Unity context is. [Here's an article about that issue](https://jacx.net/2015/11/20/dont-use-equals-null-on-unity-objects.html) – Hakej Apr 21 '21 at 12:03

0 Answers0