Tag:加入了一个延迟,在button按下状态一段时间后再開始 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; } }
在商店中购买、在背包中出售、使用一种物品的情况下。须要对button进行长按处理,来高速添加或降低 物品个数。在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 上面 (当然其他控件也能够) 。然后设置 长按的回调函数 以及 调用间隔。
长按button。就会依照设定的间隔事件 。不停得调用 指定的 OnLongPress 函数。
样例下载:
http://download.csdn.net/detail/cp790621656/8794181