How to save dictionary keycode values to PlayerPrefs with C#

Hi. I have a dictionary that holds < string, KeyCode > value pairs, but I need to save the keycode values to PlayerPrefs. From what I understand I need to convert the KeyCodes to an int or a string in order to store them. I tried converting the KeyValuePairs to a string using a forEach but I kept receiving “Cannot convert… ‘KeyValuePair’… to ‘string’”. I am still a dev rookie so I may be using improper syntax.

I did the work Googling around and I found some C# solutions but I couldn’t get some of their syntax to work in Unity. After a few hours of not getting anywhere with my research, I felt I should ask for advice and be taught how to properly do it. I appreciate any help I get on this. I’ll include my failed attempt at converting the values to a string in the 2nd class below.

The dictionary:

public class ControlKeybinds : MonoBehaviour {
	public static Dictionary < string, KeyCode > keyBinds = new Dictionary < string, KeyCode > ();
	public void SavedKeyBinds () {
		keyBinds.Add( "Player1Right", KeyCode.D );
		keyBinds.Add( "Player1Left", KeyCode.A );
	}

public class SaveKeybinds : MonoBehaviour {
	public static void SaveControlKeybinds () {
		foreach( string key in ControlKeybinds.keyBinds ) {
			var value = ControlKeybinds.keyBinds[key];
		}
	}
}

foreaching over a dictionary (like your keybinds) gives you KeyValuePairs, not the type of the keys.

You can solve this either by taking that into account, or doing a foreach over the dictionary’s .Keys property. Assuming that you do the second one, saving everything to playerprefs should be simple:

public static void SaveControlKeybinds () {
    foreach(string key in ControlKeybinds.keyBinds.Keys ) {

        //cast the enum to an int
        int intRepresentation = (int) keyBinds[key];
        
        //Save the keybind
        PlayerPrefs.SetInt(key, intRepresentation);
    }
    
    //Write the changes to disk
    PlayerPrefs.Save();
}

Every enum value has a corresponding integer value, and you can cast both ways. So if you need to retrieve say the “Player1Right” key, you can retrieve it and put it back in your dict like this:

keyBinds["Player1Right"] = (KeyCode) PlayerPrefs.GetInt("Player1Right");

Hope that helps!

I prefer compressing to one big and sloppy piece of code.

` public Dictionary<string, string> paths = new Dictionary<string, string>();

public string dict;

public void GetDict () {

	paths = new Dictionary<string, string>();

	string[] splitSemicolon = dict.Split (';');

	for (int i = 0; i < splitSemicolon.Length - 1; i++) {

		string[] keysAndValues = splitSemicolon*.Split(',');*
  •   	paths.Add (keysAndValues[0], keysAndValues[1]);*
    
  •   }*
    
  • }*
  • public void SetDict () {*
  •   dict = "";*
    
  •   foreach (string key in paths.Keys) {*
    
  •   	string val = paths[key];*
    
  •   	dict += key + "," + val + ";";*
    
  •   }*
    
  • }`*