UGUI - 长按事件实现

直接上代码:

/***************************************************
 * 文件名: UGUI_LongPressListener.cs
 * 时  间: 2015-12-12 14:42:08
 * 作  者: AnYuanLzh
 ***************************************************/

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;

public class UGUI_LongPressListener : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{   
    public float interval = 0.5f;
    public UnityEvent onLongPress = new UnityEvent();

    bool isPressing = false;
    int fingerId = -10;
    float last_time_press_down = 0f;    

    // Update is called once per frame
    void Update ()
    {
        ProcessLongPress();
    }   

    void ProcessLongPress()
    {
        if (isPressing && fingerId != -10)
        {
            Debug.Log("time: " + (Time.time - last_time_press_down));
            if (Time.time - last_time_press_down >= interval)
            {
                onLongPress.Invoke();
                last_time_press_down = Time.time;
                isPressing = false;
                fingerId = -10;
            }
        }
    }


    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("OnPointerDown");
        if (fingerId != -10) return;

        isPressing = true;
        fingerId = eventData.pointerId;
        last_time_press_down = Time.time;

    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("OnPointerUp");
        if(eventData.pointerId != fingerId) return;

        isPressing = false;
        last_time_press_down = Time.time;
        fingerId = -1;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("OnPointerExit");
        if (eventData.pointerId != fingerId) return;

        isPressing = false;
        last_time_press_down = Time.time;
        fingerId = -1;
    }
}

你可能感兴趣的:(U3D,UGUI)