Getting number keys value with new Unity Input System

Hi. I’m trying to map weapon switching to number keys. I want to pass number key value to callback function, but i don’t know how to get it or even if its possible

Please help

@kbkmn
Hello! I was running into the same issue and couldn’t find it anywhere but after playing around a bit I came up with a solution. Our problem is that when you use the

“YourInputAction.YourActionMap.SwitchWeapon.performed += ctx => print(ctx.ReadValue())”

It prints out “1” no matter what button is pressed. My solution is on each of your action bindings (the 4 bindings under your “Switch Weapon”) add a “Scale” under processors and make the scale factor the number key (1 for 1 key, 2 for 2 key, 3 for 3 key, etc). Then the ctx.ReadValue() will printed out 1 * factor which will be which number key you pressed!

I hope that helps!

,Hello! I was running into the same issue and couldn’t find it anywhere but after playing around a bit I came up with a solution. Our problem is that when you use the

“YourInputAction.YourActionMap.SwitchWeapon.performed += ctx => print(ctx.ReadValue())”

It prints out “1” no matter what button is pressed. My solution is on each of your action bindings (the 4 bindings under your “Switch Weapon”) add a “Scale” under processors and make the scale factor the number key (1 for 1 key, 2 for 2 key, 3 for 3 key, etc). Then the ctx.ReadValue() will printed out 1 * factor which will be which number key you pressed!

I hope that helps!

FWIW, if you already know that your keypress is coming from a number key (for example, you’ve bound this action to only the number keys, and not all the keys), then you can use int.TryParse on the ctx.control.name (which is a string).

(caveat: If you int.TryParse() a ctx.control.name that can’t parse to an int, you’ll still get 0, so your code might think you’ve hit the 0 key…)

 private void SetItemByKeyValue(UnityEngine.InputSystem.InputAction.CallbackContext ctx) {

            int numKeyValue; // the number key value we want from this keypress

            int.TryParse(ctx.control.name, out numKeyValue);
            // Warning! If ctx.control.name can't parse as an int, numKeyValue will be 0

            Debug.Log("int value of keypress is: " + numKeyValue);

            // Now do something with the key value ...

        }