unity3D技术分享

UnityEvent的使用方法

2020-01-17  本文已影响0人  UnityPlane

UnityEvent本质上是继承自UnityEventBase的类,它的AddListener()方法能够注册UnityAction,RemoveListener能够取消注册UnityAction,还有Invoke()方法能够一次性调用所有注册了的UnityAction。UnityEvent也有数个泛型版本(参数最多也是4个),但要注意的一点是,UnityAction的所有带参数的泛型版本都是抽象类(abstract),所以如果要使用的话,需要自己声明一个类继承之,然后再实例化该类才可以使用

unityevent是可以带参数的
首先是无参法使用

using UnityEngine;
using UnityEngine.Events;
public class Unityevent1 : MonoBehaviour
{
    UnityEvent Myevent;
    // Start is called before the first frame update
    void Start()
    {
        if (Myevent == null)
            Myevent = new UnityEvent();
        Myevent.AddListener(Ping);
    }

    private void Update()
    {
        if (Input.anyKeyDown && Myevent != null)
        {
            Myevent.Invoke();
        }
    }

    void Ping()
    {
        Debug.Log("Ping");
    }
}

其次是带有参数的使用方法

using System;
using UnityEngine;
using UnityEngine.Events;

[Serializable]
public class MyIntEvent : UnityEvent<int>//最多可以传4个值
{ 

}

public class unityevent2 : MonoBehaviour
{ 
    public MyIntEvent m_MyEvent;
    // Start is called before the first frame update
    void Start()
    {
        if (m_MyEvent == null)
            m_MyEvent = new MyIntEvent();

        m_MyEvent.AddListener(Ping);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.anyKeyDown && m_MyEvent != null)
        {
            m_MyEvent.Invoke(5); //调用传参,并传入参数,最多4个参数 
        }
    }

    void Ping(int i)
    {
        Debug.Log("Ping" + i);
    }
}

上一篇下一篇

猜你喜欢

热点阅读