- Home /
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.
Answer by Jesse Anders · Apr 20, 2011 at 04:30 AM
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).
Answer by KyleRasmusson · Sep 06, 2016 at 06:19 AM
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.
Answer by VorTer · Apr 12, 2020 at 09:41 AM
Error: Must Specify vaild information for persing in the string.
Your answer
Follow this Question
Related Questions
Check the latest key pressed? 2 Answers
Anyway to get what key is down? 1 Answer
Key not recognized 2 Answers
Problem with Custom Input Manager 1 Answer