Home > Software design >  NullReferenceException when gamepad is disconnected
NullReferenceException when gamepad is disconnected

Time:08-25

I'm using New Input system on my game and I'm having this error

NullReferenceException: Object reference not set to an instance of an object
PauseMenu.Update ()

pointing to this line:

if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)

whenever the gamepad is not connected.

void Update()
{
    var gamepad = Gamepad.current;
    var keyboard = Keyboard.current;
    if (gamepad == null && keyboard == null)
        return; // No gamepad connected.
    if (gamepad.startButton.wasPressedThisFrame || keyboard.pKey.wasPressedThisFrame)
    {

        if (GameIsPaused)
        {
            Resume();

        }
        else
        {
            Pause();
        }
    }
}

How can I fix this?

CodePudding user response:

The issue is that the exit condition requires that both keyboard and gamepad are null. In the case that gamepad is null and keyboard is not (or the other way around), an attempt is made to access a member of the null object.

You can resolve the issue by comparing each object against null before accessing its properties.

if ((gamepad != null && gamepad.startButton.wasPressedThisFrame) ||
    (keyboard != null && keyboard.pKey.wasPressedThisFrame)
)
{
    // Pause / Resume
}

You could also use the null conditional operator ? in each condition. When the preceding object is null, the resulting value is null. Then using the null coalescing operator ?? we convert this null value to a bool (false in this case because a null button cannot be "pressed").

if (gamepad?.startButton.wasPressedThisFrame ?? false ||
    keyboard?.pKey.wasPressedThisFrame ?? false)
  • Related