Skip to content

Instantly share code, notes, and snippets.

@nir1082
Last active January 12, 2018 03:15
Show Gist options
  • Save nir1082/f54e9d20031c7022e9e5e76a536fa75e to your computer and use it in GitHub Desktop.
Save nir1082/f54e9d20031c7022e9e5e76a536fa75e to your computer and use it in GitHub Desktop.
namespace UnityEngine.UI
{
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
using System;
public class LongPressButton : Selectable, IUpdateSelectedHandler, IPointerClickHandler
{
public float pressTime = 1.0f;
public bool oneShot = true;
public bool disableClickEventOnLongPressed = true;
public UnityEvent onClick;
public UnityEvent onLongPress;
private float m_BeganTime;
private bool m_IsPress;
private bool m_Ready = true;
public bool isPress {
get {
return m_IsPress;
}
}
public override void OnPointerDown (PointerEventData eventData)
{
base.OnPointerDown (eventData);
m_BeganTime = Time.realtimeSinceStartup;
m_Ready = true;
m_IsPress = true;
}
public override void OnPointerUp (PointerEventData eventData)
{
base.OnPointerUp (eventData);
m_Ready = false;
m_IsPress = false;
}
public void OnUpdateSelected (BaseEventData eventData)
{
if (m_Ready && onLongPress != null && (Time.realtimeSinceStartup - m_BeganTime >= pressTime)) {
onLongPress.Invoke ();
m_Ready = !oneShot;
}
}
public void OnPointerClick (PointerEventData eventData)
{
if (onClick != null && (!disableClickEventOnLongPressed || Time.realtimeSinceStartup - m_BeganTime < pressTime)) {
onClick.Invoke ();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment