标签:3d游戏开发 unity培训 unity3d培训 unity3d游戏 unity3d学习
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
// NotificationCenter的拓展类,在这里弄出多个INotificationCenter的子类,
// 分别处理不同的消息转发,便于消息分组
public class NotificationCenter : INotificationCenter
{
private static INotificationCenter singleton;
private event EventHandler GameOver;
private event EventHandler ScoreAdd;
private NotificationCenter()
: base()
{
// 在这里添加需要分发的各种消息
eventTable[GameOver]
= GameOver;
eventTable[ScoreAdd]
= ScoreAdd;
}
public static INotificationCenter GetInstance()
{
if (singleton == null)
singleton = new NotificationCenter();
return singleton;
}
}
// NotificationCenter的抽象基类
public abstract class INotificationCenter
{
protected Dictionarystring, EventHandler eventTable;
protected INotificationCenter()
{
eventTable = new Dictionarystring, EventHandler();
}
// PostNotification -- 将名字为name,发送者为sender,参数为e的消息发送出去
public void PostNotification(string name)
{
this.PostNotification(name, null, EventArgs.Empty);
}
public void PostNotification(string name, object sender)
{
this.PostNotification(name, name, EventArgs.Empty);
}
public void PostNotification(string name, object sender, EventArgs e)
{
if (eventTable[name]
!= null)
{
eventTable[name](sender, e);
}
}
// 添加或者移除了一个回调函数。
public void AddEventHandler(string name, EventHandler handler)
{
eventTable[name]
+= handler;
}
public void RemoveEventHandler(string name, EventHandler handler)
{
eventTable[name]
-= handler;
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class Observer : MonoBehaviour {
private INotificationCenter center;
private Dictionarystring, EventHandler handlers;
void Awake() {
handlers = new Dictionarystring, EventHandler();
center = NotificationCenter.GetInstance();
}
void OnDestroy() {
foreach (KeyValuePairstring, EventHandler kvp in handlers) {
center.RemoveEventHandler(kvp.Key, kvp.Value);
}
}
public void AddEventHandler(string name, EventHandler handler) {
center.AddEventHandler(name, handler);
handlers.Add(name, handler);
}
}
在Unity中使用事件/委托机制(event/delegate)进行GameObject之
标签:3d游戏开发 unity培训 unity3d培训 unity3d游戏 unity3d学习
原文地址:http://blog.csdn.net/book_longssl/article/details/44025629