【unity2D】API-学习记录7-事件UnityAction
作者:互联网
目标
学习UnityAction,以期简化代码。
前言
在委托Delegate里我们学习了多播委托(multicast delegate)。在C#Event中,用一个委托执行多个方法,就是多播委托。而在UnityEvent中,要实现多播委托,可以直接写,也可以使用UnityAction。
代码相关
在没用UnityAction时,我们要写多播委托,只能如下写一长串:
void OnEnable()
{
MyZombieEvent = GameObject.Find("EventTest").GetComponent<EventTest>();
MyZombieEvent.zombieEvent.AddListener(IntensifyDamage); //订阅事件
MyZombieEvent.zombieEvent.AddListener(IntensifyAttackIntermission);//订阅事件
MyZombieEvent.zombieEvent.AddListener(PeaAttack); //订阅事件
}
使用UnityAction后,可以写成这样:
void OnEnable()
{
MyZombieEvent = GameObject.Find("EventTest").GetComponent<EventTest>();
unityAction += IntensifyDamage;
unityAction += IntensifyAttackIntermission;
unityAction += PeaAttack;
}
非常简洁。
完整代码如下:
using UnityEngine;
using UnityEngine.Events;//引用命名空间
[System.Serializable]//序列化ZombieEvent,使其在Editor中显示,则可在Editor中选定订阅者
public class ZombieEvent : UnityEvent{}
//这一步对应C#Event中的“定义委托类型”
public class EventTest : MonoBehaviour
{
public ZombieEvent zombieEvent;
//这一步对应C#Event中的“基于委托类型,定义事件”
//这里的是实例事件,在上一篇中的是静态事件
void Start()
{
if(zombieEvent == null)
{
zombieEvent = new ZombieEvent();//实例化
}
zombieEvent.Invoke();//用Invoke发出通知
}
}
using UnityEngine;
using UnityEngine.Events;//引用命名空间
public class Pea : MonoBehaviour
{
public EventTest MyZombieEvent;
public UnityAction peaAction;
void OnEnable()
{
MyZombieEvent = GameObject.Find("EventTest").GetComponent<EventTest>();
peaAction += IntensifyDamage;
peaAction += IntensifyAttackIntermission;
peaAction += PeaAttack;
MyZombieEvent.zombieEvent.AddListener(peaAction);
}
void OnDisable()
{
MyZombieEvent.zombieEvent.RemoveListener(peaAction); //取消订阅
}
public void PeaAttack()
{
Debug.Log("Peas are attacking zombies.");
}
public void IntensifyDamage()
{
Debug.Log("The damage of pea double.");
}
public void IntensifyAttackIntermission ()
{
Debug.Log("The intermission of shot double.");
}
}
运行结果如图:
注意事项
根据上面的代码,我们可以看出一些端倪:
- 使用UnityAction时,该委托必须是零参数委托。详见Unity API UnityAction。
- 用UnityAction要引用命名空间:using UnityEngine.Events;
参考资料
标签:zombieEvent,unity2D,peaAction,void,MyZombieEvent,API,public,UnityAction 来源: https://www.cnblogs.com/OtusScops/p/14725993.html