Last active
October 19, 2021 21:07
-
-
Save ErikRikoo/b2bfbc9b9afadcb0faf61a0c81a176e9 to your computer and use it in GitHub Desktop.
A useful script that allows you to run the method ApplyInputValue continuously while pressing a button in the new Unity Input System
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using UnityEngine; | |
using UnityEngine.InputSystem; | |
public abstract class ContinuousInputHandler<InputType> : MonoBehaviour | |
where InputType : struct | |
{ | |
private InputType m_ReadValue; | |
private Coroutine m_CurrentCoroutine; | |
private bool m_ShouldStartOnEnable; | |
private void OnEnable() | |
{ | |
if (m_ShouldStartOnEnable) | |
{ | |
m_CurrentCoroutine = StartCoroutine(c_UpdateFromInput()); | |
m_ShouldStartOnEnable = false; | |
} | |
} | |
private void OnDisable() | |
{ | |
StopCoroutineIfPossible(); | |
} | |
public void OnActionTriggered(InputAction.CallbackContext _context) | |
{ | |
m_ReadValue = _context.ReadValue<InputType>(); | |
switch (_context.phase) | |
{ | |
case InputActionPhase.Started: | |
StartCoroutineIfNeeded(); | |
break; | |
case InputActionPhase.Canceled: | |
StopCoroutineIfPossible(); | |
break; | |
} | |
} | |
private IEnumerator c_UpdateFromInput() | |
{ | |
while (true) | |
{ | |
ApplyInputValue(m_ReadValue); | |
yield return null; | |
} | |
} | |
private void StartCoroutineIfNeeded() | |
{ | |
if (!gameObject.activeInHierarchy) | |
{ | |
m_ShouldStartOnEnable = true; | |
return; | |
} | |
if (m_CurrentCoroutine == null) | |
{ | |
m_CurrentCoroutine = StartCoroutine(c_UpdateFromInput()); | |
} | |
} | |
private void StopCoroutineIfPossible() | |
{ | |
if (m_CurrentCoroutine != null) | |
{ | |
StopCoroutine(m_CurrentCoroutine); | |
m_CurrentCoroutine = null; | |
} | |
} | |
protected abstract void ApplyInputValue(InputType _inputValue); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment