我正在为长按按钮创建一个脚本。长按按钮有效,唯一的问题是,如果长按按钮触发,我想阻止点击按钮。
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
public class LongPressButton : 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;
}
}
按钮脚本是黑色框,似乎是它构建在统一引擎中。
我知道有很多方法可以阻止事件传播到3d世界,但有没有办法阻止按钮脚本上的传播?
答案 0 :(得分:0)
我已经弄清楚了,由于事件系统的Unity限制,你需要两个脚本才能这样做。首先是长按按钮脚本:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
using UnityEngine.UI;
public class LongPressButton : 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;
public bool WasLongPressTriggered
{
get;
protected set;
}
private void Update()
{
if (isPointerDown && false == longPressTriggered)
{
if (Time.time - timePressStarted > durationThreshold)
{
longPressTriggered = true;
WasLongPressTriggered = true;
onLongPress.Invoke();
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
timePressStarted = Time.time;
isPointerDown = true;
longPressTriggered = false;
WasLongPressTriggered = false;
}
public void OnPointerUp(PointerEventData eventData)
{
isPointerDown = false;
}
public void OnPointerExit(PointerEventData eventData)
{
isPointerDown = false;
}
}
然后你需要一个新的按钮脚本来覆盖旧的基本按钮:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Button2 : Button
{
public bool PreventPropagationOnLongPress;
public override void OnPointerClick(PointerEventData eventData)
{
var longPress = GetComponent<LongPressButton>();
if (longPress == null)
{
base.OnPointerClick(eventData);
}
if(false == longPress.WasLongPressTriggered)
{
base.OnPointerClick(eventData);
}
}
}
这在编辑器中有效,尚未在移动设备上进行全面测试,可能在统一编辑器中点击点击,但在移动设备上它可以从鼠标上启动...暂时这将阻止事件传播,