0
\$\begingroup\$

New to coding so this is probably super simple, but I can't find the answer. I'm using Unity 5.4.0 and coding in C#.

Is there a variable for input keys?

I have a game I'm making and it is working good, but I want the players to be able to choose which key does what, but I don't know how to make the key presses changeable. I am using both Input.GetKeyDown(Keycode."KEY") and Input.GetKey(Keycode."KEY").

My question is: is there a variable I can use in place of the keys that I can make changeable by the players? Like a float, but instead of numbers, it uses key codes.

\$\endgroup\$
2
\$\begingroup\$

I'm still astonished Unity doesn't have editable key mapping built-in, other than their built-in launch screen which most games don't use. But anyway that's for the abstract directional input like "Horizontal"; for specific keys like you are asking, you can simply make your variable of type KeyCode:

public KeyCode jumpKey;
...
jumpKey = KeyCode.Space;
...
Input.GetKey(jumpKey);
\$\endgroup\$
6
  • 1
    \$\begingroup\$ Expounding on this, you can user PlayerPrefs or your own storage mechanism to hold these values and allow them to be modified via UI. Using the above example, you could have a UI where a player choose "Jump" and then the system waits for an input and set jumpKey equal to that input. Once saved via the UI, it can be reloaded on launch and will remain until changed again (or reset to defaults). \$\endgroup\$ Oct 20 '16 at 18:36
  • 1
    \$\begingroup\$ Towards that end, since PlayerPrefs can only store int values not KeyCode, note that KeyCodes are integers, just in an enum so that you can refer to them by name. Try (int)KeyCode.Space to cast it as an int, or (KeyCode)32 to go back. \$\endgroup\$
    – jhocking
    Oct 20 '16 at 18:58
  • \$\begingroup\$ All good points - just keep in mind that there can be input that isn't from a keyboard. Having a good UI and using Input objects can give you a much wider range of configurability (controllers, mice, et cetera). \$\endgroup\$ Oct 20 '16 at 19:01
  • \$\begingroup\$ Thank you all so much! The answer was exactly what I was looking for, I didn't know I could use KeyCode as a Variable. \$\endgroup\$
    – Isak Jones
    Oct 21 '16 at 5:50
  • \$\begingroup\$ jhocking, I'm not sure I understand what you are saying exactly. Do I have to assign a number to each key for the (int)KeyCode? \$\endgroup\$
    – Isak Jones
    Oct 21 '16 at 5:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .