I found a strange problem while programming keyboard input in Unity (v5.3.5).

public class AvatarInputMapperUnityContext : MonoBehaviour {

    private AvatarController _avatarController;

    public KeyCode JumpKey = KeyCode.Space;
    public KeyCode LeftKey = KeyCode.A;
    public KeyCode RightKey = KeyCode.D;
    public KeyCode UpKey = KeyCode.W;
    public KeyCode DownKey = KeyCode.S;
    private Dictionary<KeyCode, WeaponTags> ShotKeys; 

    void Awake () {
        _avatarController = GetComponent<AvatarController>();
        ShotKeys.Add(KeyCode.I, WeaponTags.Pistol);
        ShotKeys.Add(KeyCode.O, WeaponTags.Shotgun);

    void Update () {

        if (Input.GetKeyDown(JumpKey)){

Now, when the ShotKeys.Add... lines are commented out everything works fine. But when I uncomment them, the program never reaches the _avatarController.JumpSignal() line, and none of the other directional keys (w,a,s,d) work. What can be the reason?


Init your Dictionary in your Awake first:

ShotKeys = new Dictionary<KeyCode, WeaponTags> ();
  • \$\begingroup\$ Ah, so dumb, so dumb! Of course, you're right, thank you. \$\endgroup\$ – dargemir Jun 4 '16 at 12:17
  • \$\begingroup\$ Haha no problem, this is why I get paid the big bucks. \$\endgroup\$ – jgallant Jun 4 '16 at 12:18

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.