Skip to content

Instantly share code, notes, and snippets.

@LordNed
Created May 14, 2015 16:04
Show Gist options
  • Save LordNed/830385f0bf7918821592 to your computer and use it in GitHub Desktop.
Save LordNed/830385f0bf7918821592 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystem;
[RequireComponent(typeof(Button))]
public class ButtonClickOnHold : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public float HoldDurationThreshold = 0.5f;
private Button m_button;
private float m_lastButtonClickTime;
private bool m_isDown;
private void Awake()
{
m_button = GetComponent<Button>();
}
private void OnEnable()
{
m_lastButtonClickTime = 0f;
}
private void Update()
{
if(!m_isDown || m_lastButtonClickTime < 0f)
return;
if(Time.time - m_lastButtonClickTime > HoldDurationThreshold)
{
// This invokes whatever is registered to the button's OnClick handler. It won't however cause the button to release its visible
// press state. If you want to control that too you'll need to derive from Button, make a similar set of logic counting and force
// its state up/down.
// Also er... the button will fire OnClick a second time when the mouse is actually released, unless you set m_button.interactable = false.
// this has the side effect of making the button suddenly grey out. An alternative solution would be to make your own UnityEvent in this class,
// and listen for that event instead of the buttons... or go with deriving from the Button class again.
m_button.onClick.Invoke();
// Invalidate our last click time so that it doesn't try to invoke the button click every frame after they've passed the threshold.
m_lastButtonClickTime = -1f;
}
}
private void OnPointerDown (PointerEventData eventData)
{
m_isDown = true;
m_lastButtonClickTime = 0f;
}
private void OnPointerUp(PointerEventData eventData)
{
m_isDown = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment