Skip to content

Instantly share code, notes, and snippets.

@pr00thmatic
Created November 2, 2025 01:15
Show Gist options
  • Select an option

  • Save pr00thmatic/17333561585fb3a93771038a4282c031 to your computer and use it in GitHub Desktop.

Select an option

Save pr00thmatic/17333561585fb3a93771038a4282c031 to your computer and use it in GitHub Desktop.
a mobile touch hold detector: make sure the InputAction type is set to Button and the binding is set to "Press (Multi-Touch)", AKA: `<Touchscreen>/touch*/Press`
// a mobile touch hold detector: make sure the InputAction type is set to Button and the binding is set to "Press (Multi-Touch)", AKA: `<Touchscreen>/touch*/Press`
public class HoldDetector : MonoBehaviour
{
[SerializeField] private InputActionReference holdAction;
[SerializeField] private InputActionReference holdStartAction;
[SerializeField] private float distanceToleranceInPixels = 20;
private void OnEnable ()
{
holdAction.action.performed += HandleHoldSuccess;
holdStartAction.action.performed += HandleHoldAttempt;
}
private void OnDisable ()
{
holdAction.action.performed -= HandleHoldSuccess;
holdStartAction.action.performed -= HandleHoldAttempt;
}
private void HandleHoldAttempt (InputAction.CallbackContext context) =>
HandleHoldPerformed(context, OnHoldAttempt);
private void HandleHoldSuccess (InputAction.CallbackContext context) =>
HandleHoldPerformed(context, OnHoldSuccess);
private void HandleHoldPerformed (InputAction.CallbackContext context, UnityEvent<Vector2> eventToTrigger)
{
if (context.control.parent is not TouchControl touch)
return; // maybe it's a click or something idk...
float powToleratedDistance = Mathf.Pow(distanceToleranceInPixels, 2); // pow is cheaper than sqrt
if ((touch.startPosition.ReadValue() - touch.position.ReadValue()).sqrMagnitude <= powToleratedDistance)
eventToTrigger?.Invoke(touch.position.ReadValue());
}
public UnityEvent<Vector2> OnHoldAttempt { get; private set; } = new();
public UnityEvent<Vector2> OnHoldSuccess { get; private set; } = new();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment