0.前言
游戏开发中,消息机制是比较常见的模块间解耦工具,在此分享一个平时用的比较顺手的事件系统。
1.使用方法介绍
首先分为三个脚本
EventType:用来定义消息事件
CallBack:用委托定义消息回调方法
EventCenter:用来处理消息广播、添加、移除的核心类
使用的时候要先在EventType里先定义好消息的枚举
public enum EventType
{
Test,
ShowText,
ShowInfo,
}
然后编写一个测试脚本,用来演示消息广播
using UnityEngine;
public class EventTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
EventCenter.Broadcast(EventType.Test);
// 第一个参数填写枚举消息,后面填写消息需要携带的参数
EventCenter.Broadcast(EventType.ShowText, "hello world");
EventCenter.Broadcast(EventType.ShowInfo, "hello world", "Xiaoming", 1);
}
}
再编写一个测试脚本,用来接收消息
using UnityEngine;
public class ListenerTest : MonoBehaviour
{
// Start is called before the first frame update
void Awake()
{
// 监听无参数的消息
EventCenter.AddListener(EventType.Test, Test);
// 监听带有参数的消息,使用泛型传入参数类型
EventCenter.AddListener(EventType.ShowText, ShowText);
// 最多支持接收带有五个参数的消息,当然也可以在CallBack里继续扩展参数数量
EventCenter.AddListener(EventType.ShowInfo, ShowInfo);
}
void Test()
{
Debug.Log("no param");
}
void ShowText(string text)
{
Debug.Log(text);
}
void ShowInfo(string text, string name, int age)
{
Debug.Log(text + name + age);
}
// 最后需要在脚本销毁的时候移除监听
private void OnDestroy()
{
EventCenter.RemoveListener(EventType.Test, Test);
EventCenter.RemoveListener(EventType.ShowText, ShowText);
EventCenter.RemoveListener(EventType.ShowInfo, ShowInfo);
}
}
最后运行的效果
2.完整代码
EventCenter.cs
using System;
using System.Collections;
using System.Collections.Generic;
usi