NotifyCenter观察者模式
更像 订阅,项目需要,所以实现了一个简易的
using UnityEngine; using System.Collections; using System.Collections.Generic; public delegate void HandlerNotifyCenter(System.Object arg); [System.Serializable] class Recver { public string name; public GameObject recver; public HandlerNotifyCenter handler; public Recver() { } public void InVoke(System.Object arg) { handler(arg); } } public class NotifyCenter : MonoBehaviour { static public NotifyCenter ins; List<Recver> recvers = new List<Recver>(); void Awake() { ins = this; } // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void addRecver(GameObject recver, string name, HandlerNotifyCenter handler) { // gameObject.SendMessage(msg); Recver x = new Recver(); x.name = name; x.handler = handler; x.recver = recver; recvers.Add(x); } public void removeRecver(GameObject recver, string name) { foreach (Recver obj in recvers) { if (name == obj.name && recver == obj.recver) { recvers.Remove(obj); } } } public void sendMessage(string msg, System.Object arg) { foreach (Recver obj in recvers) { if (msg == obj.name) { obj.InVoke(arg); } } } }