# 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. selenium-05-常见问题

    一:日期控件 selenium不能直接对日期控件操作,可以通过js对日期控件做赋值操作 WebElement inputTimeBox=driver.findElement(by.name(" ...

  2. Redis数据库安装与配置调试

    主要培养自我对Redis数据库安装能力, 并且进行个性化的数据库配置.掌握本实验的重点,即在于数据库的安装与启动参数的配置.同时,理解NOSQL数据库的体系结构. ①下载Redis安装包进行数据库平台 ...

  3. Spring 梳理-跨重定向请求传递数据-Flash

    Spring MVC Flash Attribute 的讲解与使用示例 1. Spring MVC 3.1版本加了一个很有用的特性,Flash属性,它能解决一个长久以来缺少解决的问题,一个POST/R ...

  4. Android蓝牙低功耗(BLE)模块设计

    在阅读这篇文章之前你应该对GATT和Android蓝牙框架有一定的了解.这里不会向你解释Service.Characteristics等蓝牙知识.这里只是我写下我对Android Ble的再次封装来适 ...

  5. Ubuntu下安装并使用sublime text 3(建议:先安装Package controls 后在看本教程,否则可能会安装不了)

    首先从Sublime Text官网下载合适的包 然后使用 tar -xvvf sublime_text_3_build_3207_x64.tar.bz2 解压: 再使用 mv sublime_text ...

  6. redis查找大key

    redis中查找出比较大的key 下面直接上代码 (请在测试机上测试) #!/usr/bin/env python import sys import redis def check_big_key( ...

  7. Docker 为非root用户授权

    Docker 为非root用户授权: 当运行docker pull busybox时候,会提示sky用户无法调用docker. 那么应该把sky用户加入docker用户组,不过在添加的时候,又提示了如 ...

  8. ELK 学习笔记之 Logstash之filter配置

    Logstash之filter: json filter: input{ stdin{ } } filter{ json{ source => "message" } } o ...

  9. node 利用命令行交互生成相应模板

    目录 readline 实现 使用process实现 使用 inquirer 调用的生成模板方法 (generator 方法) 创建时间:2019-10-15 测试环境:win10 node-v10. ...

  10. c语言程序设计2

    c语言秋季作业2 问题 答案 这个作业属于哪个课程 C语言程序设计Ⅰ 这个作业要求在哪里 [c语言博客作业02](https://edu.cnblogs.com/campus/zswxy/SE2019 ...