So, I’m really curious about this issue. My Dictionary is set on Start, and never is anything removed. However, when I release my ‘Jump’ Key, line 39 sometimes throws an error - where I try to increase the float value in the dictionary. Unity tells me that the Value is null. I don’t even know how a float can be null.
Can anyone help me?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour {
public delegate void InputPressed();
public static event InputPressed LeftPressed;
public static event InputPressed RightPressed;
public static event InputPressed JumpPressed;
private static Dictionary<InputPressed, float> eventAndTimeSinceLastPress = new Dictionary<InputPressed, float>();
private void Start()
{
eventAndTimeSinceLastPress.Add(LeftPressed, 0);
eventAndTimeSinceLastPress.Add(RightPressed, 0);
eventAndTimeSinceLastPress.Add(JumpPressed, 0);
}
private void Update()
{
HandleInput(LeftPressed, KeyCode.LeftArrow);
HandleInput(RightPressed, KeyCode.RightArrow);
HandleInput(JumpPressed, KeyCode.UpArrow);
}
void HandleInput(InputPressed i_event, KeyCode i_key)
{
if (Input.GetKey(i_key))
{
if (i_event == null) { return; }
i_event();
eventAndTimeSinceLastPress[i_event] = 0;
}
else
{
eventAndTimeSinceLastPress[i_event] += Time.deltaTime;
}
}
}