- Home /
Question by
z3nth10n · Apr 17, 2014 at 03:21 PM ·
nullreferenceexceptiondictionarykeycode
Adding keys to a static Dictionary doesn't keep the values at the end of the function
Hi,
well I use static variables because it isn't destroyed at the end of the function... So, I have that code:
public class mInput {
public static Dictionary<string, KeyCode> inputMap;
public static void LoadAllKeysFromConfig() {
inputMap = new Dictionary<string, KeyCode>();
inputMap.Add("Exp", GetKeyFromString("L"));
inputMap.Add("Kill", GetKeyFromString("K"));
inputMap.Add("FPS", GetKeyFromString("F10"));
inputMap.Add("EnableGUI", GetKeyFromString("F1"));
inputMap.Add("GameMenu", GetKeyFromString("Escape"));
inputMap.Add("Inv", GetKeyFromString("E"));
inputMap.Add("Waypoint", GetKeyFromString("P"));
inputMap.Add("ToggleMap", GetKeyFromString("M"));
inputMap.Add("SwitchView", GetKeyFromString("V"));
inputMap.Add("TakeScreenShot", GetKeyFromString("F2"));
inputMap.Add("Laser", GetKeyFromString("L"));
inputMap.Add("FlashLight", GetKeyFromString("F"));
inputMap.Add("Reload", GetKeyFromString("R"));
inputMap.Add("Console", GetKeyFromString("F12"));
inputMap.Add("SendCommand", GetKeyFromString("Return"));
inputMap.Add("Unlock", GetKeyFromString("U"));
}
private static KeyCode GetKeyFromString(string KeyStr, bool IgnoreCase = true) {
return (KeyCode)System.Enum.Parse(typeof(KeyCode), KeyStr, IgnoreCase);
}
}
(I call LoadAllKeysFromConfig() from a Start() function from another script)
But when I want to request some control, NullReferenceException appears, why?
Thanks in advance. Bye.
Comment
Best Answer
Answer by NoseKills · Apr 17, 2014 at 05:04 PM
The code itself seems to work. Are you sure there are no calls to inputMap before you run LoadAllKeysFromConfig() the first time ?
To ensure this you could make a getter (since the values are hardcoded and all)
private static Dictionary<string, KeyCode> inputMap;
public static Dictionary<string, KeyCode> InputMap {
get {
if (inputMap == null)
{
LoadAllKeysFromConfig();
}
return inputMap;
}
}
Your answer
