unity 消息分发
来源:互联网 发布:厂家销售软件 编辑:程序博客网 时间:2024/06/05 19:07
有2种方法,第一种,封装U3D中的发消息函数,自己写一个事件机制出来。第2种,用C#内置的事件机制。
第一种方法,下面这个类是Digital-tutors出的Unity Mobile Game Development这一套教程里06.Communication with Notification Center里的事件机制类,他是用JS写的,我把这个脚本翻译成了C#的。并加了详细的中文注释。本质是一个观察者模式的实现,该类是一个单例的类,用哈希表来保存场景中的所有消息,哈希表中每个键值对,表示的是【某一消息(函数名)——该消息的所有观察者线性表】。最终以u3d api的SendMessage函数将消息发了过去,所以只能传递一个数据实参,受SendMessage函数本身限制。但是你传的参数可以是脚本对象,把参数写到对象中,这样就可以传多个参数了。
=======================NotificationCenter.cs======================================================
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// 2013年8月23日11:19:44,郭志程
/// <summary>
/// 信息中心类,用来处理GameObjects相互发消息。本质是观察者模式。
/// 通过AddObserver函数注册观察者,RemoveObserver注销观察者。
/// 内部通过哈希表对场景中所有的消息进行管理
/// </summary>
public class NotificationCenter : MonoBehaviour {
private static NotificationCenter defaultCenter = null;
/// <summary>
/// 单例模式, 在场景中自动造一个挂有NotificationCenter脚本的Default Notification Center游戏物体,如果手动创建了一个则不再创建
/// </summary>
public static NotificationCenter DefaultCenter () {
if (null == defaultCenter) {
GameObject notificationObject = new GameObject("Default Notification Center");
defaultCenter = notificationObject.AddComponent<NotificationCenter>();
}
return defaultCenter;
}
// 哈希表包含了所有的发送的信息。其中每个键值对,表示的是【某一消息——该消息的所有观察者线性表】
private Hashtable notifications = null;
void Awake() {
this.notifications = new Hashtable();
}
/// <summary>
/// 注册观察者
/// </summary>
public void AddObserver(Component observer, string name) { AddObserver(observer, name, null); }
public void AddObserver(Component observer, string name, Component sender) {
// 对观察者的名字进行检查
if (name == null || name == "") { Debug.Log("在AddObserver函数中指定的是空名称!."); return; }
// 哈希表中的值是List,new list
if (null == this.notifications[name]) {
this.notifications[name] = new List<Component>();
}
// 该条消息的所有观察者,通过List将他拉出来对其操作
List<Component> notifyList = this.notifications[name] as List<Component>;
// 将观察者加入到哈希表中值LIST中去,也就是注册上了
if (!notifyList.Contains(observer)) { notifyList.Add(observer); }
}
/// <summary>
/// 注销观察者
/// </summary>
public void RemoveObserver(Component observer, string name) {
// 该条消息的所有观察者,通过List将他拉出来对其操作
List<Component> notifyList = this.notifications[name] as List<Component>;
第一种方法,下面这个类是Digital-tutors出的Unity Mobile Game Development这一套教程里06.Communication with Notification Center里的事件机制类,他是用JS写的,我把这个脚本翻译成了C#的。并加了详细的中文注释。本质是一个观察者模式的实现,该类是一个单例的类,用哈希表来保存场景中的所有消息,哈希表中每个键值对,表示的是【某一消息(函数名)——该消息的所有观察者线性表】。最终以u3d api的SendMessage函数将消息发了过去,所以只能传递一个数据实参,受SendMessage函数本身限制。但是你传的参数可以是脚本对象,把参数写到对象中,这样就可以传多个参数了。
=======================NotificationCenter.cs======================================================
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// 2013年8月23日11:19:44,郭志程
/// <summary>
/// 信息中心类,用来处理GameObjects相互发消息。本质是观察者模式。
/// 通过AddObserver函数注册观察者,RemoveObserver注销观察者。
/// 内部通过哈希表对场景中所有的消息进行管理
/// </summary>
public class NotificationCenter : MonoBehaviour {