HotkeyController.cs 1.35 KB
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// If you set up your hotkeys using this, it's much easier to track them down and turn them off!
/// </summary>
public class HotkeyController : MonoBehaviour
{
    [System.Serializable]
    public class HotkeyEvent
    {
        public string buttonName;
        //public KeyCode key;
        public int numPresses = 1;
        public float maxTime = 0;
        public UnityEngine.Events.UnityEvent eventAction;

        private int _currPresses;
        private float _currTime = 0;

        public void ButtonPressed()
        {
            _currPresses++;
        }

        public void Update()
        {
            if (_currPresses == 0) return;

            if (_currPresses >= numPresses)
            {
                eventAction.Invoke();
                Reset();
            }

            _currTime += Time.deltaTime;

            if (_currTime >= maxTime)
                Reset();
        }

        private void Reset()
        {
            _currPresses = 0;
            _currTime = 0;
        }
    }

    public HotkeyEvent[] hotkeyEvents;

    void Update()
    {
        foreach (HotkeyEvent evnt in hotkeyEvents)
        {
            if (Input.GetButtonDown(evnt.buttonName))
                evnt.ButtonPressed();

            evnt.Update();
        }
    }
}