Better way to read keyboard input?

I’m working on a maths game, targeting iOS, Android and WebGL. There’s an on-screen number pad for the touch users, but I need to support keyboard input as well. Currently I’m using this approach:

void CheckInput()
{
    int input;
   
    if (Input.GetKeyDown(KeyCode.Alpha0) || Input.GetKeyDown(KeyCode.Keypad0))
        input = 0;
    else if (Input.GetKeyDown(KeyCode.Alpha1) || Input.GetKeyDown(KeyCode.Keypad1))
        input = 1;
    else if (Input.GetKeyDown(KeyCode.Alpha2) || Input.GetKeyDown(KeyCode.Keypad2))
        input = 2;
    else if (Input.GetKeyDown(KeyCode.Alpha3) || Input.GetKeyDown(KeyCode.Keypad3))
        input = 3;
    else if (Input.GetKeyDown(KeyCode.Alpha4) || Input.GetKeyDown(KeyCode.Keypad4))
        input = 4;
    else if (Input.GetKeyDown(KeyCode.Alpha5) || Input.GetKeyDown(KeyCode.Keypad5))
        input = 5;
    else if (Input.GetKeyDown(KeyCode.Alpha6) || Input.GetKeyDown(KeyCode.Keypad6))
        input = 6;
    else if (Input.GetKeyDown(KeyCode.Alpha7) || Input.GetKeyDown(KeyCode.Keypad7))
        input = 7;
    else if (Input.GetKeyDown(KeyCode.Alpha8) || Input.GetKeyDown(KeyCode.Keypad8))
        input = 8;
    else if (Input.GetKeyDown(KeyCode.Alpha9) || Input.GetKeyDown(KeyCode.Keypad9))
        input = 9;
    else if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
        input = 10;
    else if (Input.GetKeyDown(KeyCode.Backspace))
        input = -1;
    else
        return;

    _inputs.Enqueue(input);
}

That’s called from the Update method, then I’m reading off _inputs (which is a Queue<int>) in the FixedUpdate method.

So I’m calling Input.GetKeyDown 23 times every frame, which feels wasteful. Is there a better way?

(I’m a Unity noob but very experienced C# programmer.)

If you use Unity’s new input system you can do an event-based approach with the keyboard like I’m doing here:

Then you could parse the char to a number or whatever you need to do.

1 Like

Awesome, that’s worked great. Thanks for the help.

1 Like