来说说Unity观察者(Observer)模式

来源:互联网 发布:55海淘 知乎 编辑:程序博客网 时间:2024/06/05 20:49

何为观察者模式,大家都比较形象的例子,和报纸的订阅差不多,订阅者就属于观察者,我想要订阅报纸了,然后就像报刊社订阅报纸,然后每天都有邮递员向您这送报纸,不想订阅了,就自己取消,然后第二天就不会有人给你送报纸。我们来利用Delegate实现一个简单的观察着模式.

创建一个消息封装体Class,用来传递需要的消息

using System;using UnityEngine;namespace UniEventDispatcher{//时间分发着public class Notification{public GameObject m_sender;public object m_param;public Notification (GameObject  sender,object param){m_sender = sender;m_param = param;}public Notification (object param){m_sender = null;m_param = param;}public string getSring(){return string.Format("sender = {0},param = {1}",m_sender,m_param);}}}
创建一个单例的主题。

using System.Collections;using System.Collections.Generic;using UnityEngine;namespace UniEventDispatcher{public class NotificationCenter{///<summary>///定义事件分发委托///</summary>public delegate void onNotificaton(Notification notific);public onNotificaton  m_onNotificaton;public void Notice(Notification notific){if(m_onNotificaton != null){m_onNotificaton (notific);}}///<summary>///通知单例中心///</summary>private static NotificationCenter instance = null;public static NotificationCenter Get(){if(instance == null){instance = new NotificationCenter ();return instance;}return instance;}}}

我们来创建一个观察者脚本

using System.Collections;using System.Collections.Generic;using UnityEngine;using UniEventDispatcher;public class ObserverObjects : MonoBehaviour {// Use this for initializationvoid Start () {NotificationCenter.Get ().m_onNotificaton += changeColor;}void changeColor(Notification  notification){Debug.Log ("notification:getParam() : "+ notification.getSring());GetComponent< Renderer> ().material.color = (Color)notification.m_param;}// Update is called once per framevoid Update () {}void OnDestory(){NotificationCenter.Get ().m_onNotificaton -= changeColor;}}
创建一个发布者脚本

using System;using UnityEngine;using UnityEngine.UI;using UniEventDispatcher;public  class SubjectObjects :  MonoBehaviour{public Slider m_SliderA;public Slider m_SliderB;public Slider m_SliderC;void Start(){m_SliderA = GameObject.FindWithTag ("SliderA").GetComponent<Slider> ();m_SliderB = GameObject.FindWithTag ("SliderB").GetComponent<Slider> ();m_SliderC = GameObject.FindWithTag ("SliderC").GetComponent<Slider> ();m_SliderA.onValueChanged.AddListener(onChangeColor);m_SliderB.onValueChanged.AddListener(onChangeColor);m_SliderC.onValueChanged.AddListener(onChangeColor);}public void onChangeColor(float f){float r = m_SliderA.value;float g = m_SliderB.value;float b = m_SliderC.value;//发布消息NotificationCenter.Get ().Notice (new Notification(new Color (r, g, b)));}}

3,创建如下的图




原创粉丝点击