enum中使用中文 unity_Unity游戏开发——基于枚举的事件系统

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值