Tag:添加了一个延迟,在按钮按下状态一段时间后再开始 repeate
using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; using System.Collections; public class RepeatPressEventTrigger : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler { public float interval = 0.1f; //回调触发间隔时间; public float delay = 1.0f;//延迟时间; public UnityEvent onLongPress = new UnityEvent(); private bool isPointDown = false; private float lastInvokeTime; private float m_Delay = 0f; // Use this for initialization void Start() { m_Delay = delay; } // Update is called once per frame void Update() { if (isPointDown) { if ((m_Delay -= Time.deltaTime) > 0f) { return; } if (Time.time - lastInvokeTime > interval) { //触发点击; onLongPress.Invoke(); lastInvokeTime = Time.time; } } } public void OnPointerDown(PointerEventData eventData) { isPointDown = true; m_Delay = delay; } public void OnPointerUp(PointerEventData eventData) { isPointDown = false; m_Delay = delay; } public void OnPointerExit(PointerEventData eventData) { isPointDown = false; m_Delay = delay; } }
在商店中购买、在背包中出售、使用一种物品的情况下,需要对按钮进行长按处理,来快速增加或减少 物品个数。在Unity的 GUI中有一个RepeatButton可以用,在NGUI中有OnPressed 回调可以使用,但是在 UGUI 中的 Button 并没有这种功能,就需要自己添加。
原理:
处理 Unity 的点击事件
IPointerDownHandler IPointerUpHandler IPointerExitHandler
代码:
using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; using System.Collections; public class RepeatPressEventTrigger :MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IPointerExitHandler { public float interval=0.1f; [SerializeField] UnityEvent m_OnLongpress=new UnityEvent(); private bool isPointDown=false; private float lastInvokeTime; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(isPointDown) { if(Time.time-lastInvokeTime>interval) { //触发点击; m_OnLongpress.Invoke(); lastInvokeTime=Time.time; } } } public void OnPointerDown (PointerEventData eventData) { m_OnLongpress.Invoke(); isPointDown = true; lastInvokeTime = Time.time; } public void OnPointerUp (PointerEventData eventData) { isPointDown = false; } public void OnPointerExit (PointerEventData eventData) { isPointDown = false; } }
使用方法:
把脚本挂在 Button 上面 (当然其它控件也可以) ,然后设置 长按的回调函数 以及 调用间隔。
长按按钮,就会按照设定的间隔事件 ,不停得调用 指定的 OnLongPress 函数。
例子下载:
http://download.csdn.net/detail/cp790621656/8794181