纳金网
标题:
对uGUI长按事件的改进
[打印本页]
作者:
王者再临
时间:
2015-10-13 07:21
标题:
对uGUI长按事件的改进
突然发现之前写的按钮长按在两个长按按钮重叠的时候会出现问题,具体情况是按了一个按钮会执行两个按钮的事件,不重叠则没有些问题。对于这个问题,根本原因是长按的时候按的是哪一个按钮,对此修改脚本以解决该问题。
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[AddComponentMenu("UI/LongPressButton")]
public class UILongPressButton : Selectable, 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 && IsPressed() && interactable)
{
if (isLongpress)
{
if (Time.time - lastInvokeTime > interval)
{
m_onLongPress.Invoke();
lastInvokeTime = Time.time;
}
}
else
{
isLongpress = Time.time - touchBegin > longPressDelay;
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
base.OnPointerDown(eventData);
touchBegin = Time.time;
isTouchDown = true;
}
public void OnPointerExit(PointerEventData eventData)
{
base.OnPointerExit(eventData);
isTouchDown = false;
isLongpress = false;
}
public void OnPointerUp(PointerEventData eventData)
{
base.OnPointerUp(eventData);
isTouchDown = false;
isLongpress = false;
}
}
复制代码
欢迎光临 纳金网 (http://old.narkii.com/club/)
Powered by Discuz! X2.5