unity获取button的长按,双击 button类扩展
using UnityEngine;using UnityEngine.UI;
using UnityEngine.EventSystems;
/// <summary>
/// 我的自定义Button,继承 Button
/// </summary>
public class ExtraButton : Button
{
// 构造函数
protected ExtraButton()
{
doubleClickEvent = new ButtonClickedEvent();
longPressEvent = new ButtonClickedEvent();
}
// 双击
public ButtonClickedEvent doubleClickEvent;
public ButtonClickedEvent onDoubleClick
{
get { return doubleClickEvent; }
set { doubleClickEvent = value; }
}
// 长按
public ButtonClickedEvent longPressEvent;
public ButtonClickedEvent onLongPress
{
get { return longPressEvent; }
set { longPressEvent = value; }
}
// 长按需要的变量参数
private bool my_isStartPress = false;
private float my_curPointDownTime = 0f;
private float my_longPressTime = 0.6f;
private bool my_longPressTrigger = false;
void Update()
{
CheckIsLongPress();
}
#region 长按
/// <summary>
/// 处理长按
/// </summary>
void CheckIsLongPress() {
if (my_isStartPress && !my_longPressTrigger)
{
if (Time.time > my_curPointDownTime + my_longPressTime)
{
my_longPressTrigger = true;
my_isStartPress = false;
if (longPressEvent != null)
{
longPressEvent.Invoke();
}
}
}
}
public override void OnPointerDown(PointerEventData eventData)
{
// 按下刷新當前時間
base.OnPointerDown(eventData);
my_curPointDownTime = Time.time;
my_isStartPress = true;
my_longPressTrigger = false;
}
public override void OnPointerUp(PointerEventData eventData)
{
// 指針擡起,結束開始長按
base.OnPointerUp(eventData);
my_isStartPress = false;
}
public override void OnPointerExit(PointerEventData eventData)
{
// 指針移出,結束開始長按,計時長按標志
base.OnPointerExit(eventData);
my_isStartPress = false;
}
#endregion
#region 双击(单击)
public override void OnPointerClick(PointerEventData eventData)
{
//(避免已經點擊進入長按后,擡起的情況)
if (!my_longPressTrigger)
{
Debug.Log("eventData.clickCount"+eventData.clickCount);
// 正常單擊
if (eventData.clickCount == 2 )
{
if (doubleClickEvent != null)
{
doubleClickEvent.Invoke();
}
}// 雙擊
else if (eventData.clickCount == 1)
{
onClick.Invoke();
}
}
}
#endregion
} 替换原有的Button组件,如果在lua中,直接用 self.objBtnSpin:GetComponent("ExtraButton").onClick:AddListener(
function()
print("onClick")
end
)
self.objBtnSpin:GetComponent("ExtraButton").onLongPress:AddListener(
function()
print("OnLongPress")
end
)
self.objBtnSpin:GetComponent("ExtraButton").onDoubleClick:AddListener(
function()
print("onDoubleClick")
end
)参考链接:https://blog.csdn.net/u014361280/article/details/107603869
页:
[1]