Search Unity

Better way to read keyboard input?

Discussion in 'Scripting' started by mark_rendle, Nov 3, 2020.

  1. mark_rendle

    mark_rendle

    Joined:
    Feb 22, 2019
    Posts:
    24
    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:

    Code (CSharp):
    1. void CheckInput()
    2. {
    3.     int input;
    4.    
    5.     if (Input.GetKeyDown(KeyCode.Alpha0) || Input.GetKeyDown(KeyCode.Keypad0))
    6.         input = 0;
    7.     else if (Input.GetKeyDown(KeyCode.Alpha1) || Input.GetKeyDown(KeyCode.Keypad1))
    8.         input = 1;
    9.     else if (Input.GetKeyDown(KeyCode.Alpha2) || Input.GetKeyDown(KeyCode.Keypad2))
    10.         input = 2;
    11.     else if (Input.GetKeyDown(KeyCode.Alpha3) || Input.GetKeyDown(KeyCode.Keypad3))
    12.         input = 3;
    13.     else if (Input.GetKeyDown(KeyCode.Alpha4) || Input.GetKeyDown(KeyCode.Keypad4))
    14.         input = 4;
    15.     else if (Input.GetKeyDown(KeyCode.Alpha5) || Input.GetKeyDown(KeyCode.Keypad5))
    16.         input = 5;
    17.     else if (Input.GetKeyDown(KeyCode.Alpha6) || Input.GetKeyDown(KeyCode.Keypad6))
    18.         input = 6;
    19.     else if (Input.GetKeyDown(KeyCode.Alpha7) || Input.GetKeyDown(KeyCode.Keypad7))
    20.         input = 7;
    21.     else if (Input.GetKeyDown(KeyCode.Alpha8) || Input.GetKeyDown(KeyCode.Keypad8))
    22.         input = 8;
    23.     else if (Input.GetKeyDown(KeyCode.Alpha9) || Input.GetKeyDown(KeyCode.Keypad9))
    24.         input = 9;
    25.     else if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
    26.         input = 10;
    27.     else if (Input.GetKeyDown(KeyCode.Backspace))
    28.         input = -1;
    29.     else
    30.         return;
    31.  
    32.     _inputs.Enqueue(input);
    33. }
    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.)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    mark_rendle likes this.
  3. mark_rendle

    mark_rendle

    Joined:
    Feb 22, 2019
    Posts:
    24
    Awesome, that's worked great. Thanks for the help.
     
    PraetorBlue likes this.