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?