Unity消息简易框架 Advanced C# messenger
Unity消息简易框架 Advanced C# messenger
【转载 雨凇MOMO博客】 https://www.xuanyusong.com/archives/2165
Tips
在寻找Unity下好用的消息事件框架的时候无意中发现该框架,十分简易,但又用起来特别方便。公司VR游戏中试了下,真滴方便。也不造轮子了,直接转载雨凇大佬的博客,就当是Mark一下,方便以后学习。
正文
Advanced CSharp Messenger 属于C#事件的一种。 维基百科中由详细的说明http://wiki.unity3d.com/index.php?title=Advanced_CSharp_Messenger 上周的一天刚巧有朋友问到我这一块的知识,那么我研究出来将它贴在博客中,帮助了他也帮助我自己!哇咔咔。
Advanced CSharp Messenger的特点可以将游戏对象做为参数发送。到底Advanced CSharp Messenger有什么用呢?先创建一个立方体对象,然后把Script脚本绑定在这个对象中。脚本中有一个方法叫DoSomething()。写一段简单的代码,通常我们在调用方法的时候需要这样来写。
- private Script script;
- void Awake()
- {
- GameObject cube = GameObject.Find("Cube");
- script = cube.GetComponent<Script>();
- }
- void Update()
- {
- if(Input.GetMouseButtonDown(0))
- {
- script.DoSomething();
- }
- }
代码比较简单,我就不注释了。 原理就是先获取游戏对象,接着获取脚本组件对象,最后通过脚本组件对象去调用对应脚本中的方法,这样的调用方法我们称之为直接调用。
这个例子中我只调用了一个对象的方法,如果说有成千上万个对象,那么这样调用是不是感觉自己的代码非常的丑?因为你需要一个一个的获取对象然后获取脚本组件然后在调用方法。。。。。 (想想都恐怖!!)
下面我们在用Advanced CSharp Messenger来实现事件的调用。按照维基百科中首先把Message.cs 和Callback.cs拷贝在你的工程中。
CallBack.cs
- public delegate void Callback();
- public delegate void Callback<T>(T arg1);
- public delegate void Callback<T, U>(T arg1, U arg2);
- public delegate void Callback<T, U, V>(T arg1, U arg2, V arg3);
Message.cs
- /*
- * Advanced C# messenger by Ilya Suzdalnitski. V1.0
- *
- * Based on Rod Hyde's "CSharpMessenger" and Magnus Wolffelt's "CSharpMessenger Extended".
- *
- * Features:
- * Prevents a MissingReferenceException because of a reference to a destroyed message handler.
- * Option to log all messages
- * Extensive error detection, preventing silent bugs
- *
- * Usage examples:
- 1. Messenger.AddListener<GameObject>("prop collected", PropCollected);
- Messenger.Broadcast<GameObject>("prop collected", prop);
- 2. Messenger.AddListener<float>("speed changed", SpeedChanged);
- Messenger.Broadcast<float>("speed changed", 0.5f);
- *
- * Messenger cleans up its evenTable automatically upon loading of a new level.
- *
- * Don't forget that the messages that should survive the cleanup, should be marked with Messenger.MarkAsPermanent(string)
- *
- */
- //#define LOG_ALL_MESSAGES
- //#define LOG_ADD_LISTENER
- //#define LOG_BROADCAST_MESSAGE
- #define REQUIRE_LISTENER
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- static internal class Messenger {
- #region Internal variables
- //Disable the unused variable warning
- #pragma warning disable 0414
- //Ensures that the MessengerHelper will be created automatically upon start of the game.
- static private MessengerHelper messengerHelper = ( new GameObject("MessengerHelper") ).AddComponent< MessengerHelper >();
- #pragma warning restore 0414
- static public Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();
- //Message handlers that should never be removed, regardless of calling Cleanup
- static public List< string > permanentMessages = new List< string > ();
- #endregion
- #region Helper methods
- //Marks a certain message as permanent.
- static public void MarkAsPermanent(string eventType) {
- #if LOG_ALL_MESSAGES
- Debug.Log("Messenger MarkAsPermanent \t\"" + eventType + "\"");
- #endif
- permanentMessages.Add( eventType );
- }
- static public void Cleanup()
- {
- #if LOG_ALL_MESSAGES
- Debug.Log("MESSENGER Cleanup. Make sure that none of necessary listeners are removed.");
- #endif
- List< string > messagesToRemove = new List<string>();
- foreach (KeyValuePair<string, Delegate> pair in eventTable) {
- bool wasFound = false;
- foreach (string message in permanentMessages) {
- if (pair.Key == message) {
- wasFound = true;
- break;
- }
- }
- if (!wasFound)
- messagesToRemove.Add( pair.Key );
- }
- foreach (string message in messagesToRemove) {
- eventTable.Remove( message );
- }
- }
- static public void PrintEventTable()
- {
- Debug.Log("\t\t\t=== MESSENGER PrintEventTable ===");
- foreach (KeyValuePair<string, Delegate> pair in eventTable) {
- Debug.Log("\t\t\t" + pair.Key + "\t\t" + pair.Value);
- }
- Debug.Log("\n");
- }
- #endregion
- #region Message logging and exception throwing
- static public void OnListenerAdding(string eventType, Delegate listenerBeingAdded) {
- #if LOG_ALL_MESSAGES || LOG_ADD_LISTENER
- Debug.Log("MESSENGER OnListenerAdding \t\"" + eventType + "\"\t{" + listenerBeingAdded.Target + " -> " + listenerBeingAdded.Method + "}");
- #endif
- if (!eventTable.ContainsKey(eventType)) {
- eventTable.Add(eventType, null );
- }
- Delegate d = eventTable[eventType];
- if (d != null && d.GetType() != listenerBeingAdded.GetType()) {
- throw new ListenerException(string.Format("Attempting to add listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being added has type {2}", eventType, d.GetType().Name, listenerBeingAdded.GetType().Name));
- }
- }
- static public void OnListenerRemoving(string eventType, Delegate listenerBeingRemoved) {
- #if LOG_ALL_MESSAGES
- Debug.Log("MESSENGER OnListenerRemoving \t\"" + eventType + "\"\t{" + listenerBeingRemoved.Target + " -> " + listenerBeingRemoved.Method + "}");
- #endif
- if (eventTable.ContainsKey(eventType)) {
- Delegate d = eventTable[eventType];
- if (d == null) {
- throw new ListenerException(string.Format("Attempting to remove listener with for event type \"{0}\" but current listener is null.", eventType));
- } else if (d.GetType() != listenerBeingRemoved.GetType()) {
- throw new ListenerException(string.Format("Attempting to remove listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being removed has type {2}", eventType, d.GetType().Name, listenerBeingRemoved.GetType().Name));
- }
- } else {
- throw new ListenerException(string.Format("Attempting to remove listener for type \"{0}\" but Messenger doesn't know about this event type.", eventType));
- }
- }
- static public void OnListenerRemoved(string eventType) {
- if (eventTable[eventType] == null) {
- eventTable.Remove(eventType);
- }
- }
- static public void OnBroadcasting(string eventType) {
- #if REQUIRE_LISTENER
- if (!eventTable.ContainsKey(eventType)) {
- throw new BroadcastException(string.Format("Broadcasting message \"{0}\" but no listener found. Try marking the message with Messenger.MarkAsPermanent.", eventType));
- }
- #endif
- }
- static public BroadcastException CreateBroadcastSignatureException(string eventType) {
- return new BroadcastException(string.Format("Broadcasting message \"{0}\" but listeners have a different signature than the broadcaster.", eventType));
- }
- public class BroadcastException : Exception {
- public BroadcastException(string msg)
- : base(msg) {
- }
- }
- public class ListenerException : Exception {
- public ListenerException(string msg)
- : base(msg) {
- }
- }
- #endregion
- #region AddListener
- //No parameters
- static public void AddListener(string eventType, Callback handler) {
- OnListenerAdding(eventType, handler);
- eventTable[eventType] = (Callback)eventTable[eventType] + handler;
- }
- //Single parameter
- static public void AddListener<T>(string eventType, Callback<T> handler) {
- OnListenerAdding(eventType, handler);
- eventTable[eventType] = (Callback<T>)eventTable[eventType] + handler;
- }
- //Two parameters
- static public void AddListener<T, U>(string eventType, Callback<T, U> handler) {
- OnListenerAdding(eventType, handler);
- eventTable[eventType] = (Callback<T, U>)eventTable[eventType] + handler;
- }
- //Three parameters
- static public void AddListener<T, U, V>(string eventType, Callback<T, U, V> handler) {
- OnListenerAdding(eventType, handler);
- eventTable[eventType] = (Callback<T, U, V>)eventTable[eventType] + handler;
- }
- #endregion
- #region RemoveListener
- //No parameters
- static public void RemoveListener(string eventType, Callback handler) {
- OnListenerRemoving(eventType, handler);
- eventTable[eventType] = (Callback)eventTable[eventType] - handler;
- OnListenerRemoved(eventType);
- }
- //Single parameter
- static public void RemoveListener<T>(string eventType, Callback<T> handler) {
- OnListenerRemoving(eventType, handler);
- eventTable[eventType] = (Callback<T>)eventTable[eventType] - handler;
- OnListenerRemoved(eventType);
- }
- //Two parameters
- static public void RemoveListener<T, U>(string eventType, Callback<T, U> handler) {
- OnListenerRemoving(eventType, handler);
- eventTable[eventType] = (Callback<T, U>)eventTable[eventType] - handler;
- OnListenerRemoved(eventType);
- }
- //Three parameters
- static public void RemoveListener<T, U, V>(string eventType, Callback<T, U, V> handler) {
- OnListenerRemoving(eventType, handler);
- eventTable[eventType] = (Callback<T, U, V>)eventTable[eventType] - handler;
- OnListenerRemoved(eventType);
- }
- #endregion
- #region Broadcast
- //No parameters
- static public void Broadcast(string eventType) {
- #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
- Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
- #endif
- OnBroadcasting(eventType);
- Delegate d;
- if (eventTable.TryGetValue(eventType, out d)) {
- Callback callback = d as Callback;
- if (callback != null) {
- callback();
- } else {
- throw CreateBroadcastSignatureException(eventType);
- }
- }
- }
- //Single parameter
- static public void Broadcast<T>(string eventType, T arg1) {
- #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
- Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
- #endif
- OnBroadcasting(eventType);
- Delegate d;
- if (eventTable.TryGetValue(eventType, out d)) {
- Callback<T> callback = d as Callback<T>;
- if (callback != null) {
- callback(arg1);
- } else {
- throw CreateBroadcastSignatureException(eventType);
- }
- }
- }
- //Two parameters
- static public void Broadcast<T, U>(string eventType, T arg1, U arg2) {
- #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
- Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
- #endif
- OnBroadcasting(eventType);
- Delegate d;
- if (eventTable.TryGetValue(eventType, out d)) {
- Callback<T, U> callback = d as Callback<T, U>;
- if (callback != null) {
- callback(arg1, arg2);
- } else {
- throw CreateBroadcastSignatureException(eventType);
- }
- }
- }
- //Three parameters
- static public void Broadcast<T, U, V>(string eventType, T arg1, U arg2, V arg3) {
- #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
- Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
- #endif
- OnBroadcasting(eventType);
- Delegate d;
- if (eventTable.TryGetValue(eventType, out d)) {
- Callback<T, U, V> callback = d as Callback<T, U, V>;
- if (callback != null) {
- callback(arg1, arg2, arg3);
- } else {
- throw CreateBroadcastSignatureException(eventType);
- }
- }
- }
- #endregion
- }
- //This manager will ensure that the messenger's eventTable will be cleaned up upon loading of a new level.
- public sealed class MessengerHelper : MonoBehaviour {
- void Awake ()
- {
- DontDestroyOnLoad(gameObject);
- }
- //Clean up eventTable every time a new level loads.
- public void OnDisable() {
- Messenger.Cleanup();
- }
- }
然后就可以开始使用了,Messager.Broadcast()这样就好比我们发送了一条广播。
- void Update()
- {
- if(Input.GetMouseButtonDown(0))
- {
- Messenger.Broadcast("Send");
- }
- }
在需要这条广播的类中来接受它,同样是刚刚说的Script类。接受广播的标志是 Messager.AddListener()参数1表示广播的名称,参数2表示广播所调用的方法。
- using UnityEngine;
- using System.Collections;
- public class Script : MonoBehaviour {
- void Awake()
- {
- Messenger.AddListener( "Send", DoSomething );
- }
- public void DoSomething()
- {
- Debug.Log("DoSomething");
- }
- }
这样一来,只要发送名称为”Send”的方法,就可以在别的类中接收它了。
我们在说说如何通过广播来传递参数,这也是那天那个哥们主要问我的问题。(其实是维基百科上写的不是特别特别的清楚,那哥们误解了)在Callback中可以看出参数最多可以是三个,参数的类型是任意类型,也就是说我们不仅能传递 int float bool 还能传递gameObject类型。
如下所示,发送广播的时候传递了两个参数,参数1是一个游戏对象,参数2是一个int数值。
- void Update()
- {
- if(Input.GetMouseButtonDown(0))
- {
- GameObject cube = GameObject.Find("Cube");
- Messenger.Broadcast<GameObject,int>("Send",cube,1980);
- }
- }
然后是接受的地方 参数用<>存在一起。游戏对象也可以完美的传递。
- using UnityEngine;
- using System.Collections;
- public class Script : MonoBehaviour {
- void Awake()
- {
- Messenger.AddListener<GameObject,int>( "Send", DoSomething );
- }
- public void DoSomething(GameObject obj,int i)
- {
- Debug.Log("name " + obj.name + " id =" + i);
- }
- }
如果传递一个参数
两个参数<T,T>
三个参数<T,T,T>
怎么样使用起来还是挺简单的吧?
我觉得项目中最好不要大量的使用代理事件这类的方法(根据需求而定),虽然可以让你的代码非常的简洁,但是它的效率不高大概比直接调用慢5-倍左右吧,就好比美好的东西一定都有瑕疵一样。 还记得Unity自身也提供了一种发送消息的方法吗?,用过的都知道效率也非常低下,虽然我们看不到它具体实现的源码是如何实现的,但是我觉得原理可能也是这样的。 欢迎和大家一起讨论与学习。
转载于:https://www.cnblogs.com/Firepad-magic/p/9484304.html
Unity消息简易框架 Advanced C# messenger相关推荐
- Unity项目UI管理简易框架
一.背景 在一个Unity项目中或多或少需要一些UI,如设置页面,登录页面等,当页面过多时,使用一个通用的UI框架来进行针对性开发会大大减少造轮子的过程. 以下即为参考之前做过的一些项目整理出来的一个 ...
- C#使用Advanced CSharp Messenger
Advanced CSharp Messenger 属于C#事件的一种. 维基百科中由详细的说明http://wiki.unity3d.com/index.php?title=Advanced_CSh ...
- WPF仿微信界面发送消息简易版
WPF仿微信界面发送消息简易版 参考别的博主的例子用WPF MVVM框架来仿了一个微信聊天界面,做了个发送消息简易功能,下面一起来看看吧! 以下为View视图布局代码,消息对话框的样式直接在这里定义了 ...
- unity 实现简易打飞碟游戏
unity 实现简易打飞碟游戏 一.简介 游戏共有5个回合,每个回合中会有随机产生的飞碟飞过屏幕,玩家需要做的事情就是用鼠标尽量快和多地点击飞碟. 每个飞碟对应一定的分数,目前的设置是: [红色飞碟 ...
- [Unity] C#使用委托和事件实现Unity消息中心(观察者模式)
前言: 最近在学习ue的gameplay框架设计和设计模式,再回过头看一下自己过去一年写的unity项目框架(屎山)代码,感慨良多.体会到做游戏写脚本,语言语法只是表层功夫,学会它可以让游戏跑起来.走 ...
- “一切都是消息”--iMSF(即时消息服务框架)入门简介
"一切都是消息"--这是iMSF(即时消息服务框架)的设计哲学. MSF的名字是 Message Service Framework 的简称,由于目前框架主要功能在于处理即时(im ...
- “一切都是消息”--iMSF(即时消息服务框架)之【请求-响应】模式(点对点)...
MSF的名字是 Message Service Framework 的简称,由于目前框架主要功能在于处理即时(immediately)消息,所以iMSF就是 immediately Message S ...
- java 进程通信框架,MediatR-进程内的消息通信框架
MediatR是一款进程内的消息订阅.发布框架,提供了Send方法用于发布到单个处理程序.Publish方法发布到多个处理程序,使用起来非常方便.目前支持 .NET Framework4.5..NET ...
- android 功能防抖,一款简单的消息防抖框架
WQthrottle 是一款消息防抖框架,在一定的时间延时中做到只触发一次结果的回调. 使用 使用的话,还是看 github 的 README 吧. 开发目的 开发这款框架的初衷是为了解决以下的几个痛 ...
最新文章
- tomcat7 内存溢出 java.lang.OutOfMemoryError: Java heap space
- php判断当前时间是否跨月,判断日期是否能跨月查询的js代码_javascript技巧
- Xamarin 从零开始部署 iOS 上的 Walterlv.CloudKeyboard 应用
- oracle 参照完整性,Oracle中用表外键来保证系统参照完整性
- oracle排序函数性能,oracle排序函数
- 7收不到邮件 contact form_Contact Form 7基本使用教程
- symantec:硝基***针对化工厂商
- [Leetcode] Reorder List
- 为什么互联网公司天天都在招人?
- 2018-2019年全球专业服务机器人销售额增长32%,达到112亿美元
- 【QQ空间批量下载高清照片问题】
- c语言自评报告怎么写,大学生学生自评报告怎么写
- 【免费分享】论文查重软件(亲测好用!)
- Python爬虫爬企查查数据
- 软件测试cpu性能测试案例,性能测试之用例得分评价和 CPU 内存数据监控——谈谈个人看法和实践总结...
- SNS2124(OEM博科FC交换机)忘记密码,密码初始化
- java关于数组的下标越界
- linux 存储映射lun 给_LINUX系统下添加映射存储LUN
- POJ,ZOJ题目分类(多篇整合版,分类很细致,全面)
- JAVASCRIPT中THIS指的是什么?
热门文章
- sql server 数据库 ' ' 附近有语法错误
- windows哪些版本可以免费升级win10
- vue 中eslint 格式报错
- 偷天换日——新型浏览器劫持木马“暗影鼠”分析
- 【移动开发】Android中三种超实用的滑屏方式汇总(ViewPager、ViewFlipper、ViewFlow)...
- C++接口定义及实现举例
- mysql用dos窗口即cmd命令登陆mysql
- CentOS6.0搭建DNS
- extmail集群的邮件负载均衡方案 [lvs dns postfix]
- [Linux网络编程学习笔记]套接字地址结构