Unity UGUI Button 按下,抬起,连续按下,鼠标退出事件响应函数

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
///


/// 脚本位置:UGUI按钮组件身上
/// 脚本功能:实现按钮长按状态的判断
/// 创建时间:2017
///

// 继承:按下,抬起和离开的三个接口
public class OnButtonPressed :MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IPointerExitHandler
{
// 延迟时间
private float delay = 0.2f;

// 按钮是否是按下状态  
private bool isDown = false;  

// 按钮最后一次是被按住状态时候的时间  
private float lastIsDownTime;  



void Update ()  
{  
    // 如果按钮是被按下状态  
    if (isDown) {  
    // 当前时间 -  按钮最后一次被按下的时间 > 延迟时间0.2秒  
        if (Time.time - lastIsDownTime > delay) {  
            // 触发长按方法  
            Debug.Log("长按");  
            // 记录按钮最后一次被按下的时间  
            lastIsDownTime = Time.time;  

        }  
    }  

}  

// 当按钮被按下后系统自动调用此方法  
public void OnPointerDown (PointerEventData eventData)  
{  
    isDown = true;  
    lastIsDownTime = Time.time;  
}  

// 当按钮抬起的时候自动调用此方法  
public void OnPointerUp (PointerEventData eventData)  
{  
    isDown = false;  
}  

// 当鼠标从按钮上离开的时候自动调用此方法  
public void OnPointerExit (PointerEventData eventData)  
{  
    isDown = false;  
}  

}

==========================================
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;

public class test : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler, IPointerClickHandler
{
public float interval = 0.1f;

[SerializeField]  
UnityEvent m_OnLongpress = new UnityEvent();  
private bool isPointDown = false;  
private float lastInvokeTime;  


// Update is called once per frame  
void Update()  
{  
    if (isPointDown)  
    {  
        if (Time.time - lastInvokeTime > interval)  
        {  
            //触发点击;  
            m_OnLongpress.Invoke();  
            lastInvokeTime = Time.time;  
            Debug.Log("长按");  
        }  
    }  
}  


public void OnPointerDown(PointerEventData eventData)  
{  
    m_OnLongpress.Invoke();  


    isPointDown = true;  


    lastInvokeTime = Time.time;  
    Debug.Log("鼠标按下");  
}  


public void OnPointerUp(PointerEventData eventData)  
{  
    isPointDown = false;  
    Debug.Log("鼠标抬起");  
}  


public void OnPointerExit(PointerEventData eventData)  
{  
    isPointDown = false;  
    Debug.Log("鼠标退出");  
}  
public void OnPointerClick(PointerEventData eventData)  
{  
    isPointDown = false;  
    Debug.Log("鼠标点击");  
}  

}

你可能感兴趣的:(Unity UGUI Button 按下,抬起,连续按下,鼠标退出事件响应函数)