Saving KeyCode in PlayerPrefs

Is there a way to turn a saved string in player prefs back into a keycode. (Or is there a better way of saving key preferences?) e.g.

upKey = PlayerPrefs.GetString("upKey", KeyCode.UpArrow.ToString());

// This results in Assets/Scripts/Game/PlayerSettings.js(15,48): BCE0022: Cannot convert 'String' to 'UnityEngine.KeyCode'.

2 Answers

2

You can use string representations of enums just fine. All you have to do is this to parse it back to an enum (in C#):

  KeyCode keycodeResult = (KeyCode)Enum.Parse( typeof(KeyCode), yourString );

KeyCode is an enum, so you need to use ints -

upKey = PlayerPrefs.GetInt("upKey", parseInt( KeyCode.UpArrow ) );

Thanks, that works. (Although I had to move it out of where it was in my class constructor, or Unity complained that I was calling GetInt somewhere other than the main thread).

–