Input Manager (From string to keycode)

Hi everyone,

Is there a way to convert stringnames from the input manager to the actual keycodes ?

For example: There is a button called "Attack", at the resolution dialog you have assigned the 'a'-key to the "Attack" button.

Now, I'm searching for a function to return the 'a'-key by giving the strinf name "Attack". Is this possible in Unity ?

Thank you in advance.

You can use Enum.Parse to convert a string into the associated enumerant. However, the string will have to match the name of the enumerant exactly. If you want to use different names for display purposes, you'll need an additional layer of indirection (e.g. a dictionary mapping your control names to the key code names).

Because this still shows up in Related Questions, I thought I’d add on to this since I just figured out an answer earlier today.

If you can, I’d recommend saving whatever string you’re using to PlayerPrefs so that you can use this KeyCode across scenes, or even allow it to be changeable in the future.

Here’s what I’ve gotten

KeyCode Up, Down, Left, Right, Jump;

    if (PlayerPrefs.HasKey("Up"))
        Up = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Up"));

    if (PlayerPrefs.HasKey("Down"))
        Down = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Down"));

    if (PlayerPrefs.HasKey("Left"))
        Left = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Left"));

    if (PlayerPrefs.HasKey("Right"))
        Right = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Right"));

    if (PlayerPrefs.HasKey("Jump"))
        Jump = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Jump"));

This takes the KeyCode, gets the string, and converts your string into the KeyCode. It looks like thats what’s being used, but if you’re not saving to PlayerPrefs, you can just remove that part, and I haven’t tested this, but I believe you could remove the PlayerPrefs.GetString and just pass in your string and it should work.
Defining the PlayerPrefs is off on another script. Here’s the tutorial that I used to write all this.

Error: Must Specify vaild information for persing in the string.