設計模式--觀察者模式(一)
阿新 • • 發佈:2018-12-18
1.unity 目錄結構如下:
2. canvas 下掛如下四個指令碼
Subject.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// 事件派發類,所有發生的事件都是由這個類來派發的 /// </summary> /// public class Subject : MonoBehaviour { public delegate void ObserverTest(); public static event ObserverTest ObserverTestEvent; private void Start() { Button btn = transform.Find("Button").GetComponent<Button>(); btn.onClick.AddListener(OnClick); } public void OnClick(){ if (ObserverTestEvent != null) { ObserverTestEvent(); } } }
ButtonObserver.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtonObserver : MonoBehaviour { // Use this for initialization void Start () { // 註冊事件 Subject.ObserverTestEvent += ChangeButton; } public void ChangeButton(){ Button button = transform.Find("Button (1)").GetComponent<Button>(); Image image = button.GetComponent<Image>(); Text text = button.GetComponentInChildren<Text>(); image.color = Color.yellow; text.text = "On Change Button Color"; } private void OnDestroy() { // 結束時登出事件 Subject.ObserverTestEvent -= ChangeButton; } }
TextObserver_1.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextObserver_1 : MonoBehaviour { // Use this for initialization void Start () { Subject.ObserverTestEvent += ChangeText; } /// <summary> /// 改變文字內容 /// </summary> public void ChangeText(){ Text text = transform.Find("Text").GetComponent<Text>(); text.text = "Hi,第一個李勝福"; } private void OnDestroy() { Subject.ObserverTestEvent -= ChangeText; } }
TextOberver_2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextOberver_2 : MonoBehaviour {
// Use this for initialization
void Start () {
Subject.ObserverTestEvent += ChangeText;
}
/// <summary>
/// 改變第二個文字的內容
/// </summary>
void ChangeText(){
Text text = transform.Find("Text (1)").GetComponent<Text>();
text.text = "Hi,第二個李勝福";
}
private void OnDestroy()
{
Subject.ObserverTestEvent -= ChangeText;
}
}
3.效果圖如下: