Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

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?