- Home /
Why are my keybinds not saving?
I can't figure out why my keybinds aren't loading when I relaunch my game after saving them. I can see the playerprefs keybinds have saved inside the registry. I feel like I'm accidentally setting the keybinds back to default and it's not reading what I saved previously.
CODE:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class KeyBindScript : MonoBehaviour { private Dictionary keys = new Dictionary (); private GameObject currentKey;
private Color32 normal = new Color32(39, 171, 249, 255);
private Color32 selected = new Color32(239, 116, 36, 255);
public Text forward, backward, strafeL, strafeR, jump;
void Start()
{
keys.Add("Forward", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Forward", "W")));
keys.Add("Backward", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Backward", "S")));
keys.Add("StrafeL", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("StrafeL", "A")));
keys.Add("StrafeR", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("StrafeR", "D")));
keys.Add("Jump", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Jump", "Space")));
forward.text = keys["Forward"].ToString();
backward.text = keys["Backward"].ToString();
strafeL.text = keys["StrafeL"].ToString();
strafeR.text = keys["StrafeR"].ToString();
jump.text = keys["Jump"].ToString();
}
public void OnGUI()
{
if (currentKey != null)
{
Event e = Event.current;
if (e.isKey)
{
keys[currentKey.name] = e.keyCode;
currentKey.transform.GetChild(0).GetComponent<Text>().text = e.keyCode.ToString();
currentKey.GetComponent<Image>().color = normal;
currentKey = null;
}
}
}
public void ChangeKey(GameObject clicked)
{
if (currentKey != null)
{
currentKey.GetComponent<Image>().color = normal;
}
currentKey = clicked;
currentKey.GetComponent<Image>().color = selected;
}
public void SaveKeys()
{
foreach (var key in keys)
{
PlayerPrefs.SetString(key.Key, key.Value.ToString());
}
PlayerPrefs.Save();
Debug.Log("Player Prefs have saved.");
}
public void DefaultKeys()
{
PlayerPrefs.DeleteAll();
Debug.Log("Playerprefs have been deleted.");
}
}
btnApply has an On Click () set to Runtime Only KeyBindScript.SaveKeys KeyBindManager
Answer by browne11 · May 25, 2018 at 02:30 AM
I'm not sure how you're even running that code. Dictionaries must be declared somewhere.
Try removing the default values:
keys.Add("Forward", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Forward")));
Answer by Mandals · May 25, 2018 at 04:56 PM
I figured it out.
Instead of referencing the button I was referencing the text on the button, so the keybinds would just default.
Incorrect: keys.Add("Forward", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Forward", "W"))); Corrected: keys.Add("Forward", (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("btnForward", "W")));