if (inventoryUI != null)
{
inventoryUI.SetActive(!inventoryUI.activeSelf);
gameManagerMaster.isInventoryUIOn = !gameManagerMaster.isInventoryUIOn;
gameManagerMaster.CallInventoryUIToggle();
}
Code like this is something that most programmers do a lot when they start coding, then over time they realize that it’s almost always a very bad thing to do.
What happens is, they realize that NullReferenceException can happen very easily in many situations, so to “fix” the situation, they start putting these null checks everywhere.
So when a method is called with bad data, it just silently does nothing, instead of allowing an exception to be thrown.
The short term benefit of doing this is that you might turn bugs that used to be game-stopping bugs into lesser bugs.
Maybe before the != null fix, your UI manager was getting completely stuck when OpenUI threw an exception, and now the inventory just never opens. So it’s clearly better and makes for a more stable game, right?!
The problem with this is that you are basically ignoring the real source of the bug by hiding one symptom of it. It’s like shooting the messenger.
Why was inventoryUI null in the first place? Should we assign the reference in Awake instead of Start? Did we forget to disable the player inputs between level loading? Was it destroyed as a side-effect of something?
The more error hiding you do, the more likely it is that the real issues never get fixed. Also, it gets harder and harder to find the source of a problem, when you don’t immediately see an error message when something is unexpectedly null.
Being aware of possible exceptions and preparing for them is a good thing, but just adding if(x != null) is not a good method of preparation.
If it should be possible to call a method and for it to fail to do it’s intended task, you should always notify the caller about it, so that it can react accordingly. For example this would make a lot more sense:
/// <summary> Open the inventory if possible at this time. </summary>
/// <returns> True if inventory was opened, false if not. </returns>
public bool TryOpenUI()
{
if(inventoryUI == null)
{
return false;
}
...
Now the caller clearly knows that the method can fail to open the UI from just the name of the method, and it has a way to detect when this happens, so that it can react accordingly. It is then for example less likely to get stuck waiting for the onInventoryClosed callback that never takes place, because the inventory was never opened in the first place.