unity_每日随笔_MyButton

来源:互联网 发布:回收站数据恢复 免费 编辑:程序博客网 时间:2024/06/05 09:09

1,继承自unity自带的Button组件。

2,三个回调函数,分别是:按下,抬起,是否长按(长按+点击)

3,判断长按的时间:使用Invoke函数做判断。

4,重写Button类的按下和抬起函数,做为触发机制。

代码如下:

 using UnityEngine.UI;
using UnityEngine.EventSystems;
public class MyButton : Button {
    public float m_fLongPress;
    public delegate void VoidDelegate();
    public VoidDelegate onDown;
    public VoidDelegate onUp;

    public delegate void BoolDelegate(bool bClickOrPress);
    public BoolDelegate onLongPress;

    private bool isPress;

    void Start() {
        m_fLongPress = 1f;
        isPress = false;
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        if (this.interactable == false)
            return;
        if (onLongPress != null)

    1,如果按下,那一定是点击或者长按
            isPress = true;
            Invoke("onLongPressFun", m_fLongPress);
        if (onDown != null)
            onDown();
    }


    public override void OnPointerUp(PointerEventData eventData)
    {
        base.OnPointerUp(eventData);
        if (this.interactable == false)
            return;
        CancelInvoke("onLongPressFun");

1,如果已经触发长按了,那一定为假,如果没有,则一定为真

2,前提是有按下才会有抬起,所以isPress初始化由down控制

        if (isPress)
        {
            isPress = false;
            if (onLongPress != null)
                onLongPress(false); 
        }       
        if (onUp != null)
            onUp();        
    }

    public void onLongPressFun() {
        if (isPress)
        {
            isPress = false;
            if (onLongPress != null)
                onLongPress(true);
            CancelInvoke("onLongPressFun");
        }
    }
}

调用代码如下:

void Start () {
        MyButton tmpBtn = transform.GetComponent<MyButton>();
        tmpBtn.onDown = () => { print("i am down"); };
        tmpBtn.onUp = () => { print("i am up"); };
        tmpBtn.onLongPress = (bool b) =>
        {

1,是点击还是长按的判断
            if (b)
                print("is longPress");
            else
                print("is click");            
        };
}