uGUI长按事件
时间:2016-2-25 作者:new 分类: Unity游戏研究
突然发现uGUI没有给出可以直接用的长按事件。。。
上个没有注释的代码,代码说明一切。
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class UILongPressEvent : MonoBehaviour,IPointerDownHandler,IPointerExitHandler,IPointerUpHandler
{
[SerializeField]
UnityEvent m_onLongPress = new UnityEvent();
float interval = 0.1f;
float longPressDelay = 0.5f;
private bool isTouchDown = false;
private bool isLongpress = false;
private float touchBegin = 0;
private float lastInvokeTime = 0;
// Update is called once per frame
void Update ()
{
if (isTouchDown)
{
if (isLongpress)
{
if (Time.time - lastInvokeTime > interval)
{
m_onLongPress.Invoke();
lastInvokeTime = Time.time;
}
}
else
{
if (Time.time - touchBegin > longPressDelay)
{
isLongpress = true;
}
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
touchBegin = Time.time;
isTouchDown = true;
}
public void OnPointerExit(PointerEventData eventData)
{
isTouchDown = false;
isLongpress = false;
}
public void OnPointerUp(PointerEventData eventData)
{
isTouchDown = false;
isLongpress = false;
}
}