标签:unity3d
在商店中购买、在背包中出售、使用一种物品的情况下,需要对按钮进行长按处理,来快速增加或减少 物品个数。在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
UGUI 实现Button长按效果(RepeatButton)
标签:unity3d
原文地址:http://blog.csdn.net/huutu/article/details/46448313