Input.GetKey missing keyboard state on Update and FixedUpdate

I am trying to check at every FixedUpdate if the keyboard ‘right’ or ‘left’ key is pressed or not. On every FixedUpdate because that is where I am calculating and applying physics. The code is a simple:

// RIGHT
if(Input.GetKey("right"))
{
    currentInput = currentInputEnum.RIGHT;
}
// LEFT
else if(Input.GetKey("left"))
{
    currentInput = currentInputEnum.LEFT;
}
// NO INPUT
else
{
    currentInput = currentInputEnum.NOINPUT;
}

Sometimes I stop pressing the key but it doesn’t change the currentInput variable, so it keeps a wrong state. For example, sometimes I stop pressing ‘right’ and am not pressing any key, but the state stays at right; the variable stays as RIGHT.

I have tried placing the code on Update as well as FixedUpdate.

I have recorded the screen with mac’s keyboard viewer, and this variable exposed on Unity’s editor. I can see on keyboard viewer that the key was released, but the variable stays unchanged.

If I press any key, then it updates the input variable correctly, but until then it stays on the old state. Strangely, if I move my mouse it updates the variable correctly as well, even though I am not using the mouse in the game at all.

This happens about 1 in a 100 key holding situations, enough to break the game. I have tried a lot of things but am short on ideas now. I have looked elsewhere on the code to see if there is something interfering on that, but it doesn’t look like it, input is managed only on this place and this variable is set only there as well.

Any ideas on this, or how to implement a FixedUpdate key holding, continuous, detection are appreciated.

Doubt this will make a difference, but try this. If it doesn’t fix it, then I suggest looking into the new input system or using booleans instead of enums. With the new input system, you can set up delegates which trigger certain things. I recommend it :wink:

    void FixedUpdate()
    {
        currentInput = Input.GetKey("right") ? currentInputEnum.RIGHT : Input.GetKey("left") ? currentInputEnum.LEFT : currentInputEnum.NOINPUT;
    }

Maybe instead of doing else if statements you can try making them separate if statements since they aren’t mutually exclusive; Players can press right and left at the same time. I tried it in fixedupdate and it works on my end.

       if (Input.GetKey(KeyCode.RightArrow))
        {
            currentInput = InputEnum.RIGHT;

        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            currentInput = InputEnum.LEFT; 
        }

        Debug.Log(currentInput);
        if(!Input.GetKey(KeyCode.RightArrow) && !Input.GetKey(KeyCode.LeftArrow))
        {
            currentInput = InputEnum.NOINPUT;
        }

`

`