Unity uGUI 長按事件
阿新 • • 發佈:2018-12-31
在Unity 4.6新增的uGUI中,可以方便地對控制元件,通過新增EventTrigger指令碼來進行新增事件。但是裡面並沒有包括長按事件,需要自己來實現長按事件。
長按事件
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class LongPressEventTrigger : UIBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
[Tooltip("How long must pointer be down on this object to trigger a long press" )]
public float durationThreshold = 1.0f;
public UnityEvent onLongPress = new UnityEvent();
private bool isPointerDown = false;
private bool longPressTriggered = false;
private float timePressStarted;
private void Update()
{
if (isPointerDown && !longPressTriggered)
{
if (Time.time - timePressStarted > durationThreshold)
{
longPressTriggered = true;
onLongPress.Invoke();
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
timePressStarted = Time.time;
isPointerDown = true ;
longPressTriggered = false;
}
public void OnPointerUp(PointerEventData eventData)
{
isPointerDown = false;
}
public void OnPointerExit(PointerEventData eventData)
{
isPointerDown = false;
}
}
長按或點選事件
當存在長按事件,又想存在點選事件時,那麼就需要判斷是否已經執行了長按事件,已經執行了就不能再執行點選事件了,程式碼如下:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class LongPressOrClickEventTrigger : UIBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler, IPointerClickHandler
{
[Tooltip("How long must pointer be down on this object to trigger a long press")]
public float durationThreshold = 1.0f;
public UnityEvent onLongPress = new UnityEvent();
public UnityEvent onClick = new UnityEvent();
private bool isPointerDown = false;
private bool longPressTriggered = false;
private float timePressStarted;
private void Update()
{
if (isPointerDown && !longPressTriggered)
{
if (Time.time - timePressStarted > durationThreshold)
{
longPressTriggered = true;
onLongPress.Invoke();
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
timePressStarted = Time.time;
isPointerDown = true;
longPressTriggered = false;
}
public void OnPointerUp(PointerEventData eventData)
{
isPointerDown = false;
}
public void OnPointerExit(PointerEventData eventData)
{
isPointerDown = false;
}
public void OnPointerClick(PointerEventData eventData)
{
if (!longPressTriggered)
{
onClick.Invoke();
}
}
}