unity-消息的注册,监听,回调
最近在空闲时间准备做个小游戏,先把一些基本框架搭建好,本次记录的是消息的注册,监听和回调等
其实这些就是基于C#的委托(delegate)
第一步:定义一些委托
namespace Common.Messenger
{
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);
public delegate void Callback<T, U, V, W>(T arg1, U arg2, V arg3, W arg4);
public delegate void Callback<T, U, V, W, X>(T arg1, U arg2, V arg3, W arg4, X arg5);
public delegate void Callback<T, U, V, W, X, Y>(T arg1, U arg2, V arg3, W arg4, X arg5, Y arg6); public delegate T CallbackReturn<T>();
public delegate T CallbackReturn<T, U>(U arg1);
}
用泛型的方式灵活运用各种消息处理
第二步:定义两个Message类,用于add/remove/brocast消息
namespace Common.Messenger
{
public enum MessengerMode : byte
{
DONT_REQUIRE_LISTENER,
REQUIRE_LISTENER,
}
private static internal class MessengerInternal
{
//......
}
public static class Messenger
{
//....
}
}
MessengerInternal类:用于存放消息类型,结构Dictionary<string,Delegate>
static internal class MessengerInternal
{
public static Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();
public static readonly MessengerMode DEFAULT_MODE = MessengerMode.DONT_REQUIRE_LISTENER; public static void OnListenerAdding(string eventType, Delegate listenerBeingAdded)
{
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)); } public static void OnListenerMoving(string eventType,Delegate listenerBeingRemoved)
{
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));
} public static void OnListenerRemoved(string eventType)
{
if (eventTable[eventType] == null)
eventTable.Remove(eventType);
} public static void OnBroadcasting(string eventType, MessengerMode mode)
{
if(mode==MessengerMode.REQUIRE_LISTENER&&!eventTable.ContainsKey(eventType))
throw new MessengerInternal.BroadcastException(string.Format("Broadcasting message {0} but no listener found.", eventType));
} 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)
{ }
}
}
Messenger类:Public类型,用于外界的调用,封装了AddListener/Remove/Brocast的方法
public static class Messenger
{
private static Dictionary<string, Delegate> eventTable = MessengerInternal.eventTable; public static void AddListener(string eventType,Callback handler)
{
MessengerInternal.OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback)eventTable[eventType] + handler;
}
public static void RemoveListener(string eventType, Callback handler)
{
MessengerInternal.OnListenerMoving(eventType, handler);
eventTable[eventType] = (Callback)eventTable[eventType] - handler;
MessengerInternal.OnListenerRemoved(eventType);
}
public static void Broadcast(string eventType)
{
Broadcast(eventType, MessengerInternal.DEFAULT_MODE);
} public static void Broadcast(string eventType, MessengerMode mode)
{
MessengerInternal.OnBroadcasting(eventType, mode);
Delegate d;
if (eventTable.TryGetValue(eventType, out d))
{
Callback callback = d as Callback;
if (callback != null)
callback();
else
throw MessengerInternal.CreateBroadcastSignatureException(eventType);
}
}
}
Messenger<T>类:含参数的扩展类
public static class Messenger<T>
{
private static Dictionary<string, Delegate> eventTable = MessengerInternal.eventTable;
public static void AddListener(string eventType, Callback<T> handler)
{
MessengerInternal.OnListenerAdding(eventType, handler);
eventTable[eventType] = (Callback<T>)eventTable[eventType] + handler;
}
public static void RemoveListener(string eventType, Callback<T> handler)
{
MessengerInternal.OnListenerMoving(eventType, handler);
eventTable[eventType] = (Callback<T>)eventTable[eventType] - handler;
} public static void Broadcast(string eventType, T arg1)
{
Broadcast(eventType, arg1, MessengerInternal.DEFAULT_MODE);
}
public static void Broadcast(string eventType, T arg1, MessengerMode mode)
{
MessengerInternal.OnBroadcasting(eventType, mode);
Delegate d;
if (eventTable.TryGetValue(eventType,out d))
{
Callback<T> callback = d as Callback<T>;
if (callback != null)
callback(arg1);
}
else
throw MessengerInternal.CreateBroadcastSignatureException(eventType); }
}
Messenger<T, U>:同上
举例:下面是一个消息弹窗例子
UI层调用
void OnStartClick(GameObject go)
{
UIMessageMgr.ShowMessBox("?????", () => { Debug.Log("Success"); });
}
UIMessageMgr:
public static void ShowMessBox(string content, Callback ok)
{
Messenger<string, Callback>.Broadcast(MessengerEventDef.ShowMessBox, content, ok);
//MessengerEventDef.ShowMessBox 是一个string,也就是Dictionary<>中的key
}
注册:
public override void RegisterMessage()
{
Messenger<string, Callback>.AddListener(MessengerEventDef.ShowMessBox, ShowMessBox);
}
移除监听:
public override void RemoveMessage()
{
Messenger<string, Callback>.RemoveListener(MessengerEventDef.ShowMessBox, ShowMessBox);
}
以上功能就是通过消息来显示提示框,使用的Message<T,U>,普通的消息可以用Message<T>
Client和Server之间的协议通信也用消息,Message<协议类>
//Message<协议类>.AddListener("这是一个字符串",回调方法)
//回调方法
//function(协议类)
//{
// 执行内容
//}
//Remove同上
//分发消息在接收到server的消息时把消息brocast
//function(协议类)
//{
// Message<协议类>.Brocast("这是一个字符串",协议类)
//}
unity-消息的注册,监听,回调的更多相关文章
- KestrelServer详解[1]:注册监听终结点(Endpoint)
具有跨平台能力的KestrelServer是最重要的服务器类型.针对KestrelServer的设置均体现在KestrelServerOptions配置选项上,注册的终结点是它承载的最重要的配置选项. ...
- ORACLE之手动注册监听listener。alter system set local_listener="XXX"
记录下刚刚做的一个为一个数据库(t02)配置多个监听(listener)的实验,过程有点小曲折. (1)新增两个测试的监听,listener.ora的配置内容(可纯手动编辑该文件或使用netca)如下 ...
- Android View转为图片保存为本地文件,异步监听回调操作结果;
把手机上的一个View或ViewGroup转为Bitmap,再把Bitmap保存为.png格式的图片: 由于View转Bitmap.和Bitmap转图片都是耗时操作,(生成一个1M的图片大约500ms ...
- Android中添加监听回调接口的方法
在Android中,我们经常会添加一些监听回调的接口供别的类来回调,比如自定义一个PopupWindow,需要让new这个PopupWindow的Activity来监听PopupWindow中的一些组 ...
- Android学习——动态注册监听网络变化
新建一个BroadcastTest项目,然后修改MainActivity中的代码,如下: public class MainActivity extends AppCompatActivity { p ...
- android动态注册监听网络变化异常
在使用广播接收器监听网络变化的时候,在AndroidManifest.xml中加入<user-permission android:name="android.permission.A ...
- clipboard 在 vue 项目中,on 事件监听回调多次执行
clipboard 定义一个全局变量 import ClipboardJS from "clipboard"; if(clipboard){ clipboard.destroy() ...
- socket.io笔记二之事件监听回调函数接收一个客户端的回调函数
//服务端 socket.on('test', function (name, fn) { console.log(name) //输出yes fn('woot'); }); //客户端 socket ...
- Unity中的事件监听
Unity3D的uGUI系统的将UI可能触发的事件分为12个类型,即EventTriggerType枚举的12个值.如下图所示: 先以PointerClick为例.这个是用于某点点击事件.其他事件都可 ...
- javaScript学习关于常用注册监听和对象的创建
JS 中的自定义对象(扩展内容) Object 形式的自定义对象 对象的定义: ...
随机推荐
- 虚拟化KVM之优化(三)
KVM的优化 1.1 cpu的优化 inter的cpu的运行级别,(Ring2和Ring1暂时没什么用)Ring3为用户态,Ring0为内核态 Ring3的用户态是没有权限管理硬件的,需要切换到内核态 ...
- vue2.x学习笔记(二十七)
接着前面的内容:https://www.cnblogs.com/yanggb/p/12682364.html. 单元测试 vue cli拥有开箱即用的通过jest或mocha进行单元测试的内置选项.官 ...
- dlopen failed: empty/missing DT_HASH in "libx.so" (built with --hash-style=gnu?)
崩溃日志内容: java.lang.UnsatisfiedLinkError: dlopen failed: empty/missing DT_HASH in "libxxxx.so&quo ...
- 一份中外结合的 Machine Learning 自学计划
看了Siraj Raval的3个月学习机器学习计划的视频,感觉非常好,地址:https://www.youtube.com/watch?v=Cr6VqTRO1v0 结合一些我们学习中的经验得出一份Hy ...
- 有关for循环的一些东西
有的时候,不知道是因为学的有点浅显,还是脑袋有点懵,简单的循环语句都有点被绕糊涂了. 这种内外循环的,先是外循环一次,内循环全部,接着再外循环第二次,内循环全部,,,,,,,. 所以先是显示 0 4 ...
- codeforce 1311 D. Three Integers
In one move, you can add +1 or −1 to any of these integers (i.e. increase or decrease any number by ...
- predixy源码学习--开篇
最近开始研究predixy.predixy是一款高性能全功能redis代理 ,网上有的文章大部分都是功能上的介绍,很少有源码相关的分享. predixy的相关介绍在github: https://gi ...
- Springboot-WebFlux实现http重定向到https
1 简介 Spring WebFlux是一个新兴的技术,Spring团队把宝都压在响应式Reactive上了,于是推出了全新的Web实现.本文不讨论响应式编程,而是通过实例讲解Springboot W ...
- 再谈 PHP 未来之路
前段时间我写过一篇博文<phper:敢问路在何方>,分析了 PHPer 的困境以及 PHP 程序员的学习.进阶突破之路.同时我在知乎上也发过类似的提问.从大家的评论和回答看,大体分为以下几 ...
- CTF-Pwn-[BJDCTF 2nd]diff
CTF-Pwn-[BJDCTF 2nd]diff 博客说明 文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!本文仅用于学习与交流,不得用于非 ...