提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
我们在开发Unity程序的过程中会用到事件系统,除了自己开发一套监听与广播系统,也可以使用Unity中原生的监听与广播系统——UnityEvent
Unity官方文档地址:https://docs.unity3d.com/cn/2019.4/ScriptReference/Events.UnityEvent.html
一、示例代码
首先要定义所有的事件,可以写一个事件类
Events.cs
using UnityEngine.Events;
[System.Serializable]
public class Events
{
public UnityEvent zeroParaEvent;
public UnityEvent<int> oneParaEvent;
public UnityEvent<int, string> twoParaEvent;
public UnityEvent<int, string, float> threeParaEvent;
}
然后是事件广播类,在这里触发相应的广播事件
Menu.cs
using UnityEngine;
using UnityEngine.UI;
public class Menu : MonoBehaviour
{
public Button zeroBt;
public Button oneBt;
public Button twoBt;
public Button threeBt;
public Events events;
private void Start()
{
zeroBt.onClick.AddListener(() =>
{
events.zeroParaEvent.Invoke();
});
oneBt.onClick.AddListener(() =>
{
int x = 10;
events.oneParaEvent.Invoke(x);
});
twoBt.onClick.AddListener(() =>
{
int x = 10;
string s = "你好呀";
events.twoParaEvent.Invoke(x, s);
});
threeBt.onClick.AddListener(() =>
{
int x = 10;
string s = "你好呀";
float f = 12.3f;
events.threeParaEvent.Invoke(x, s, f);
});
}
}
最后是测试类,也是监听事件的地方
Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public Menu menu;
private void OnEnable()
{
menu.events.zeroParaEvent.AddListener(ZeroPare);
menu.events.oneParaEvent.AddListener(OnePara);
menu.events.twoParaEvent.AddListener(TwoPara);
menu.events.threeParaEvent.AddListener(ThreePara);
}
private void OnDisable()
{
menu.events.zeroParaEvent.RemoveListener(ZeroPare);
menu.events.oneParaEvent.RemoveListener(OnePara);
menu.events.twoParaEvent.RemoveListener(TwoPara);
menu.events.threeParaEvent.RemoveListener(ThreePara);
}
private void ZeroPare()
{
Debug.Log("没有参数");
}
private void OnePara(int x)
{
Debug.Log("一个参数,参数是:" + x);
}
private void TwoPara(int x, string s)
{
Debug.Log("两个参数,参数是:" + x + "、" + s);
}
private void ThreePara(int x, string s, float f)
{
Debug.Log("三个参数,参数是:" + x + "、" + s + "、" + f);
}
}
二、代码挂载及效果
创建四个按钮
挂载脚本,实例化按钮
创建一个空物体,将Test.cs挂载
将Menu实例化
运行效果