# 1.前言
Unity中事件/委托有着广泛的应用,本文通过封装一个简易的事件的系统,来统一管理消息的传递。此功能在简易应用或者事件较少的体现不出太好的作用,但是对于事件应用较多时,可以减少脚本之间的耦合。通过此事件系统架起不同脚本之间的桥梁,对于大量应用事件场景 中具有良好的效果。

# 2.事件系统
## 2.1 事件管理类
管理事件的注册与广播

```csharp
using System;
using System.Collections.Generic;

namespace EventManager
{
public delegate void ActionHandler(Message message);

public class EventManager
{
#region Instance
private static EventManager instance;

public static EventManager GetInstance()
{
if (instance == null)
{
instance = new EventManager();
}

return instance;
}

private EventManager() { }
#endregion

private Dictionary<string, ActionHandler> actions = new Dictionary<string, ActionHandler>();

public void AddListener(string actionKey,ActionHandler action)
{
ActionHandler handler;
bool exist = actions.TryGetValue(actionKey, out handler);

if (exist)
{
//避免重复添加
Delegate[] delegates = handler.GetInvocationList();

if (Array.IndexOf(delegates, action) == -1)
{
handler += action;
actions[actionKey] = handler;
}
}
else
{
actions.Add(actionKey, action);
}
}

public void RemoveListener(string actionKey,ActionHandler action)
{
ActionHandler handler;
bool exist = actions.TryGetValue(actionKey, out handler);

if (exist)
{
handler -= action;

if (handler == null)
{
actions.Remove(actionKey);
}
else
{
actions[actionKey] = handler;
}
}
}

public bool BroadcastMessage(string actionKey, Message message)
{
ActionHandler handler;
bool exist = actions.TryGetValue(actionKey, out handler);

if (exist)
{
handler(message);
return true;
}
else
{
return false;
}
}
}
}

```
## 2.2 消息类
通过统一的消息类来传递参数,避免泛型编程时需要考虑的多种情况。如下所示Message类,此类的参数参考android的handler类参数。可以通过继承Message的新类来传递自定义参数。

```csharp
namespace EventManager
{
public class Message
{
public int arg1;
public int arg2;
public string message;

public Message(int arg1, int arg2, string message)
{
this.arg1 = arg1;
this.arg2 = arg2;
this.message = message;
}

public Message() { }
}
}
```
## 2.3 事件标记
在EventManager中 注册事件时,通过string类型的参数来标记需要广播事件。此处可以改为枚举类型,后续可以优化。

```csharp
namespace EventManager
{
public class EventType
{
public readonly static string EVENTTYPE_METHOD1 = "EventType_Method1";
}
}
```
# 3.应用案例

```csharp
using MSG;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class EventManagerTest : MonoBehaviour
{
public Button button;

private void Start()
{

button.onClick.AddListener(() =>
{
EventManager.EventManager.GetInstance().BroadcastMessage(EventManager.EventType.EVENTTYPE_METHOD1, new EventManager.Message());
});

}

void OnEnable ()
{
EventManager.EventManager.GetInstance().AddListener(EventManager.EventType.EVENTTYPE_METHOD1, Method);
}

private void OnDisable()
{
EventManager.EventManager.GetInstance().RemoveListener(EventManager.EventType.EVENTTYPE_METHOD1, Method);
}

void Method(EventManager.Message message)
{
Debug.Log("Method : Message -{0}- obtained from channel {1}");
}

void Method1(Message message)
{
Debug.LogFormat("Method1 : Message -{0}- obtained from channel {1}", message.arg1, message.what);
}

void Method2(Message message)
{
NetworkMessage networkMessage = message as NetworkMessage;

if(networkMessage != null)
{
Debug.LogFormat("NetworkMessage obtained from channel {0}", message.what);
}
}
}

```

Unity事件系统的更多相关文章

  1. Unity事件系统EventSystem简析

    相关组件和类 EventSystem 1.负责InputModule的切换(因为现在游戏大部分都只有一个StanaloneInputModule,所以切换这部分可以先不考虑). 2.负责InputMo ...

  2. SteamVR Unity Plugin - v2.0.1中的InteractionSystem

    最近写VR项目的时候用到了SteamVR Unity Plugin - v2.0.1插件,感觉比之前用到的SteamVR plugin for Unity - v1.2.2版本改进了很多,就算不用VR ...

  3. [Unity3D] 04 - Event Manager

    message消息管理 脚本与GameObject的关系 被显式添加到 Hierarchy 中的 GameObject 会被最先实例化,GameObject 被实例化的顺序是从下往上. GameObj ...

  4. Unity 之事件系统

    游戏开发过程中事件是非常多的,可以通过 Messenger 事件系统来解藕,用法如下: 使用方法 例子:在按下拍照按钮后通知刷新好友面板 步骤1.添加事件字段,该字段具有唯一性 在MessangerE ...

  5. Unity开发心路历程——制作画板

    有人说 编程是份很无聊的工作 因为整个工作时间面对的都是电脑这种机器 因为眼睛盯着的内容都是索然无味的代码 因为总是会有意想不到的bug让你怀疑自己的智商 而我认为 编程是件及其有意思的事情 可观的收 ...

  6. Unity 4.6 uGUI的点击事件

    因为Unity 4.6刚刚发布,自带的uGUI功能的相关资料还不是很完善,今天刚装的Unity 4.6,想看一下uGUI是否好用,那么开始就今天的学习吧啊! 1,新建一个空的工程.

  7. Unity GUI选择与评价

    因为Unity内建的GUI不管是不是从开发效率或效率强制,因此,许多派生GUI插入,什么插件的选择,是一个非常值它被认为是. 既然是评价,就会有非常多的主观意识,这不一定成为选择的根据. 再比方.我已 ...

  8. Unity For Android Cardboard App ( 1 ):基础入门

    作者: ericzwhuang 前言 目前Google官方推出的VR设备有DayDream(2016年推出)和Cardboard(2014年推出)两种. Daydream是消费级VR解决方案,提供了手 ...

  9. 【Unity与23种设计模式】观察者模式(Observer)

    GoF中定义: "在对象之间定义一个一对多的连接方法,当一个对象变换状态时,其他关联的对象都会自动收到通知." 现实中,社交网络就是个例子. 以前的报社,每次出新刊的时候, 报刊便 ...

随机推荐

  1. JAVASE知识点总结(二)

    第十三章:多态  一.instanceof 判断一个类是否是指定的类 真则返回true 假则返回false.  二.字段没有多态,只有方法有多态,字段前面是的什么类型,字段就调用谁的,在编译时就已经确 ...

  2. CF #579 (Div. 3) C.Common Divisors

    C.Common Divisors time limit per test2 seconds memory limit per test256 megabytes inputstandard inpu ...

  3. Spring boot 官网学习笔记 - Configuration Class(@import)

    推荐使用 Java-based configuration ,也可以使用xml we generally recommend that your primary source be a single ...

  4. 深入理解什么是Java泛型?泛型怎么使用?【纯转】

    本篇文章给大家带来的内容是介绍深入理解什么是Java泛型?泛型怎么使用?有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所助. 一.什么是泛型 “泛型” 意味着编写的代码可以被不同类型的对象所 ...

  5. js 指定分隔符连接数组元素join()

    示例:<script type="text/javascript"> var myarr = new Array(3); myarr[0] = "I" ...

  6. Java入门学习笔记(全)

    JAVA https://zhuanlan.zhihu.com/p/21454718 引用部分实验楼代码,侵删 先通读文档 再亲自试标程 复习时自己再批注 1.a = b += c = -~d a = ...

  7. 前沿科技-混合现实(MR)远程协作辅助工具:微缩虚拟形象Mini-Me

    今天分享一篇在刚刚结束的CHI’2018上发表的full paper.该文章由来自澳洲University of South Australia的Piumsomboon等人和来自新西兰Universi ...

  8. 快学Scala 第四课 (多维数组,与Java集合的互操作)

    Scala二维数组的定义: val arr2 = Array.ofDim[String](2, 2) arr2(0)(0) = "aa" arr2(1)(0) = "bb ...

  9. 针对于ECMA5Script 、ECMAScript6、TypeScript的认识

    什么是ECMAScript.什么又是ECMA? Ecma国际(Ecma International)是一家国际性会员制度的信息和电信标准组织.1994年之前,名为欧洲计算机制造商协会(European ...

  10. GIT原理介绍

    Git 是一套内容寻址文件系统.很不错.不过这是什么意思呢? 这种说法的意思是,Git 从核心上来看不过是简单地存储键值对(key-value).它允许插入任意类型的内容,并会返回一个键值,通过该键值 ...