2
\$\begingroup\$

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)){
            _avatarController.JumpSignal();
        }
    }
}

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?

\$\endgroup\$
2
\$\begingroup\$

Init your Dictionary in your Awake first:

ShotKeys = new Dictionary<KeyCode, WeaponTags> ();
\$\endgroup\$
  • \$\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 agree to our terms of service, privacy policy and cookie policy

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