Advertisement
KpoKec

KeyInput by KeyCode with delegates

Dec 14th, 2016
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class InputController : MonoBehaviour {
  6.  
  7.     private List<KeyCode> keys = new List<KeyCode>();
  8.     private List<bool> keysDown = new List<bool>();
  9.  
  10.     public delegate void KeyPress(KeyCode key);
  11.     public event KeyPress OnKeyPress = delegate { };
  12.     public event KeyPress OnKeyHold = delegate { };
  13.     public event KeyPress OnKeyRelease = delegate { };
  14.    
  15.     public void AddKey(KeyCode _key)
  16.     {
  17.         keys.Add(_key);
  18.         keysDown.Add(false);
  19.     }
  20.     public void DeleteKey(KeyCode _key)
  21.     {
  22.         keysDown.RemoveAt(keys.IndexOf(_key));
  23.         keys.RemoveAt(keys.IndexOf(_key));
  24.     }
  25.     public void ClearKeys()
  26.     {
  27.         keys.Clear();
  28.         keysDown.Clear();
  29.     }
  30.  
  31.     void Update () {
  32.         for (int i=0; i<keys.Count; i++)
  33.         {
  34.             if (!keysDown[i] && Event.current.keyCode == keys[i])
  35.             {
  36.                 OnKeyPress(Event.current.keyCode);
  37.                 keysDown[i] = true;
  38.                 continue;
  39.             }
  40.  
  41.             if (Event.current.keyCode == keys[i] && Event.current.type == EventType.KeyUp) {
  42.                 OnKeyRelease(Event.current.keyCode);
  43.                 keysDown[i] = false;
  44.                 continue;
  45.             }
  46.  
  47.             if (keysDown[i] && Event.current.keyCode == keys[i] && Event.current.type != EventType.KeyUp)
  48.             {
  49.                 OnKeyHold(Event.current.keyCode);
  50.                 continue;
  51.             }
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement