Get keycode of pressed button
What and why? I'm making a settings menu where player can change the controls by pressing the keys they want to use for specific actions. Very basic feature.
Problem? How do I get the keycode of the buttom the player presses? To store for actual use in game.
I've tried to search for the solution...
1) Input.inputString method: Seems to work only with characters. Nope.
2) System.Enum.GetNames(typeof(KeyCode)).Length method: Excludes mouse and I'd assume the same is with controllers. Nope.
3) OnGUI method: It's 2016. Is anything "GUI" related even supported anymore?
Any other methods to do the thing?
And please, don't mention the configuration window. There is no way I'm going to enable that thing.
Answer by Nesocodon · Jul 19, 2016 at 12:25 AM
And yes, it is doable with the OnGUI() method. Below is my solution which works. But as you can see, it looks really bad and isn't 100% perfect. Is there any proper way to do this?
Can't we just have something like:
KeyCode[] keys = Input.GetKeys();
or
KeyCode[] keys = Input.GetKeys(PressMode); //PressMode = down/held/up/drag etc.
?
Or something similar to mobile touches?
void OnGUI()
{
KeyCode pressed = GetKeyCode(Event.current);
if (pressed != KeyCode.None) { print("You pressed: " + pressed); }
}
public KeyCode GetKeyCode(Event e)
{
if (e.isKey && e.keyCode != KeyCode.None) { return e.keyCode; }
if (e.isMouse) { return KeyCode.Mouse0 + e.button; }
if (e.shift)
{
if (Input.GetKey(KeyCode.RightShift)) { return KeyCode.RightShift; }
else { return KeyCode.LeftShift; }
}
if (e.alt)
{
if (Input.GetKey(KeyCode.RightAlt)) { return KeyCode.RightAlt; }
else if (Input.GetKey(KeyCode.LeftAlt)) { return KeyCode.LeftAlt; }
else { return KeyCode.AltGr; }
}
if (e.control)
{
if (Input.GetKey(KeyCode.RightControl)) { return KeyCode.RightControl; }
else { return KeyCode.LeftControl; }
}
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 9; j++)
{
if (j > 0)
{
if (Input.GetKey("joystick " + j + " button " + i))
{ return KeyCode.Joystick1Button0 + i + (j * 20); }
}
else
{
if (Input.GetKey("joystick button " + i))
{ return KeyCode.Joystick1Button0 + i + (j * 20); }
}
}
}
return KeyCode.None;
}
I don't guarantee the code works 100% with all keys...
Your answer
Follow this Question
Related Questions
About button press sprint 1 Answer
How can I change the UI button color when clicked 1 Answer
if (Input.GetKey (KeyCode.Escape)) Won't Work. 0 Answers
Check if animation is playing on button click 0 Answers
Input.GetKeyUp wont work! 1 Answer