Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Which of this 2 codes it's the best for get any key

Discussion in 'Input System' started by rubcc95, Dec 23, 2020.

  1. rubcc95

    rubcc95

    Joined:
    Dec 27, 2019
    Posts:
    222
    Option A: Getting each key one by one.
    Code (CSharp):
    1. [System.Serializable]
    2. struct EventFirer
    3. {
    4.  
    5.     [SerializeField] UnityEvent uevent;
    6.     [SerializeField] KeyCode key;
    7.  
    8.     public void Invoke()
    9.     {
    10.         if (Input.GetKey(key)) uevent.Invoke();
    11.     }
    12. }
    13.  
    14.  
    15. class EventController : MonoBehaviour
    16. {
    17.     [SerializeField] EventFirer[] firers;
    18.  
    19.     private void Update()
    20.     {
    21.         foreach (EventFirer firer in firers) firer.Invoke();
    22.     }  
    23. }
    Option B: Getting the key from Event

    Code (CSharp):
    1. [System.Serializable]
    2. struct EventFirer
    3. {
    4.  
    5.     [SerializeField] UnityEvent uevent;
    6.     [SerializeField] KeyCode key;
    7.  
    8.     public void Invoke(KeyCode current)
    9.     {
    10.         if (current == key) uevent.Invoke();
    11.     }
    12. }
    13.  
    14.  
    15. public class EventController : MonoBehaviour
    16. {
    17.     [SerializeField] EventFirer[] firers;
    18.  
    19.     void Update()
    20.     {
    21.         if (Event.current.isKey)
    22.         {
    23.             foreach (EventFirer firer in firers) firer.Invoke(Event.current.keyCode);
    24.         }
    25.     }
    26. }
    Any other idea? How you use to do it?