首页 > 代码库 > unityevent与持续按键触发

unityevent与持续按键触发

上一篇中提到一种鼠标按下时的事件触发,即采用eventtrigger设定pointerdown和pointerup并绑定相应事件。但是若要实现持续按键则需要对绑定的每个方法都添加实现持续按键方法。所以在此通过unityevent来简化过程。

(一)unityevent

unityevent为unity自定义的unity事件,需要与委托unityaction(它需要添加到event的监听中使用)。

以下为例:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class UniytEventTest : MonoBehaviour {

    UnityAction action;
    [SerializeField]
    UnityEvent actionEvent = new UnityEvent();

    public void OnTest01()
    {
        print("test01");
    }
    public void OnTest02()
    {
        print("test02");
    }
    // Use this for initialization
    void Start () {
        action = new UnityAction(OnTest01);
        action += OnTest02;

        if (action != null)
        {
            actionEvent.AddListener(action);
        }
        actionEvent.Invoke();
    }
    
    // Update is called once per frame
    void Update () {
        
    }
}

首先unityevent的特性声明

 [SerializeField]

表示此事件会出现在unity中的面板上,可以绑定事件,否则不可以。定义好事件以后就可以通过invoke方法激活一次。在此多说明一点,若通过代码绑定方法,unityaction默认为无参数的,若果需要带参数则需要通过泛型unityaction<T>来实现,但是其为抽象类需要自定义一个继承自它的来进行定义。如下

public class MyEvent:UnityEvent<int>{}
.
.
.
public MyEvent myEvent = new MyEvent();

(二)持续按键

通过unityEvent来实现持续按键,按键时事件触发时间间隔为0.1s

代码如下:

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

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

    [SerializeField]
    UnityEvent m_OnLongpress = new UnityEvent();

    private bool isPointDown = false;
    private float invokeTime;

    // Use this for initialization
    void Start()
    {
    }

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

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

        isPointDown = true;

        invokeTime = Time.time;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        isPointDown = false;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        isPointDown = false;
    }
}

 

unityevent与持续按键触发