您的位置:首页 > 移动开发 > Unity3D

Unity3D UGUI按钮长按事件

2016-07-06 15:25 405 查看
**

转载

**

原理:

处理 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity3d unity