【unity2D】API-学习记录7-事件UnityAction

2021/5/2 18:27:29

本文主要是介绍【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.");
	}
}

运行结果如图:
image

注意事项

根据上面的代码,我们可以看出一些端倪:

  1. 使用UnityAction时,该委托必须是零参数委托。详见Unity API UnityAction。
  2. 用UnityAction要引用命名空间:using UnityEngine.Events;

参考资料

Unity API UnityAction



这篇关于【unity2D】API-学习记录7-事件UnityAction的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程