Get numeric key

How I get a numeric key pressed? I can’t with the KeyCode.KeyPad neither with KeyCode.JoystickButton.

4 Answers

4

Here is another Option if someone else runs into this.

private KeyCode[] keyCodes = {
		KeyCode.Alpha1,
		KeyCode.Alpha2,
		KeyCode.Alpha3,
		KeyCode.Alpha4,
		KeyCode.Alpha5,
		KeyCode.Alpha6,
		KeyCode.Alpha7,
		KeyCode.Alpha8,
		KeyCode.Alpha9,
	};

for(int i = 0 ; i < keyCodes.Length; i ++ ){
  if(Input.GetKeyDown(keyCodes*)){*

int numberPressed = i+1;
Debug.Log(numberPressed);
}

// WUCC check for errors.
}

This is what i was exactly looking for! Thanks!

I hadn't thought of this nice, extensible way. Thank you!

I know this is old, but I love this so much.

Also, KeyCode.Alpha0 should be included.

You forgot the 0! :D

SOLVED.
is if(Input.GetKeyDown(KeyCode.Alpha1)) what I wanted but I hasn’t implementing this on a Monobehaviour class, that was the problem, although I’m using library UnityEngine and although the method that implementing this is called on a Update() from another class.
thanks

How about KeyCode.

Alpha0   The '0' key on the top of the alphanumeric keyboard.
Alpha1	 The '1' key on the top of the alphanumeric keyboard.
Alpha2	 The '2' key on the top of the alphanumeric keyboard.
Alpha3	 The '3' key on the top of the alphanumeric keyboard.
Alpha4	 The '4' key on the top of the alphanumeric keyboard.
Alpha5	 The '5' key on the top of the alphanumeric keyboard.
Alpha6	 The '6' key on the top of the alphanumeric keyboard.
Alpha7	 The '7' key on the top of the alphanumeric keyboard.
Alpha8	 The '8' key on the top of the alphanumeric keyboard.
Alpha9	 The '9' key on the top of the alphanumeric keyboard.

next time take a look at the reference material first before asking on UA

I saw that material and tested all the possibilities. with KeyCode.Alpha I also don't get numerical keys. I'm testing as follows: if(Input.GetKeyDown(KeyCode.Keypad1)) Debug.Log ("keypad..."); if(Input.GetKeyDown(KeyCode.JoystickButton1)) Debug.Log ("joystick..."); if(Input.GetKeyDown(KeyCode.Alpha1)) Debug.Log ("alpha1..."); and it don't show me anything

and the next time ask me if I saw that yet

odd. you are checking for Input inside your Update function?

I see no reason for those calls you have shown not to work for keyboard/joystick input. Is this being run in the editor?

For future reference,

Here’s an alternative to detect keycodes 0-9, avoiding a block of if statements or setting up enums/arrays and forloops!

Using System;
if(Input.inputString != ""){
    int number;
    bool is_a_number = Int32.TryParse(Input.inputString, out number);
    if (is_a_number && number >= 0 && number < 10){
        // do some work
    }
}