- Home /
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
What do you mean? Surely you just need a mono behaviour to invoke an event if any of those keys are pressed no?
But that said why would you need to do that when all monobehaviours have access to consu$$anonymous$$g those events anyway using Input.GetKey and Input.GetKeyDown and the KeypadN values.
Answer by ChipWhiteside · Jun 12, 2020 at 10:02 AM
@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!
This is a neat little trick. You'd think that it would be easy to do this kind of thing. Does anyone know the recommended way to do this?
Answer by MikeM1970 · May 07, 2021 at 12:00 AM
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 ...
}