/// <summary> /// Start a new listener and that listens to the identified keycode, and executes it's onInput event when the right input is detected. /// Each listener requires a unique ID to be able to stop the listener later on. /// </summary> /// <param name="id"></param> /// <param name="keyCode"></param> /// <param name="onInput"></param> /// <param name="stopType"></param> public static void StartListening(string id, KeyCode keyCode, Action onInput, InputListenerKeyType keyType = InputListenerKeyType.GetKey, InputListenerStopType stopType = InputListenerStopType.Manual) { ListenerData foundListenerDataWithIdenticalID = GetListenerData(id); if (foundListenerDataWithIdenticalID != null) { Debug.LogError("A listener with id " + id + " already exists!"); return; } ListenerData foundListenerData = GetListenerData(keyCode, keyType, stopType); if (foundListenerData == null) { Dictionary <string, Action> onInputEventsById = new Dictionary <string, Action>(); onInputEventsById.Add(id, onInput); ListenerData listenerData = new ListenerData() { KeyCode = keyCode, KeyType = keyType, StopType = stopType, OnInputEventsById = onInputEventsById, }; listenerDataContainer.Add(listenerData); Coroutine listenerCoroutine = CoroutineHelper.Start(ListenToInput(keyCode, keyType, stopType)); listenerData.ListenerCoroutine = listenerCoroutine; } else { foundListenerData.OnInputEventsById.Add(id, onInput); } }
private static ListenerData GetListenerData(KeyCode keyCode, InputListenerKeyType keyType, InputListenerStopType stopType) { ListenerData foundListenerData = listenerDataContainer.Find(listenerData => { bool match = keyCode == listenerData.KeyCode && keyType == listenerData.KeyType && stopType == listenerData.StopType; return(match); }); return(foundListenerData); }
private static IEnumerator ListenToInput(KeyCode keyCode, InputListenerKeyType keyType, InputListenerStopType stopType) { Func <KeyCode, bool> keyCheck = null; switch (keyType) { case InputListenerKeyType.GetKeyDown: keyCheck = x => Input.GetKeyDown(x); break; case InputListenerKeyType.GetKey: keyCheck = x => Input.GetKey(x); break; case InputListenerKeyType.GetKeyUp: keyCheck = x => Input.GetKeyUp(x); break; } while (true) { while (!keyCheck(keyCode)) { yield return(null); } ListenerData listenerData = GetListenerData(keyCode, keyType, stopType); List <Action> onInputs = listenerData.OnInputEventsById.Values.ToList(); foreach (Action onInput in onInputs) { if (onInput != null) { onInput(); } } if (stopType == InputListenerStopType.Automatic) { break; } yield return(null); } }