設計模式之觀察者模式
發佈者:定義事件成員,以及事件觸發函數
using UnityEngine;
using System.Collections;
using System;
public class BirdController : MonoBehaviour
{
// 定義事件成員
public event Action GameOver;
public event Action<int> ScoreAdd;
private void OnGUI()
{
// 事件觸發
if (GUI.Button(new Rect(10, 10, 150, 100), "投降"))
{
GameOver?.Invoke();
}
if (GUI.Button(new Rect(10, 200, 150, 100), "加10分"))
{
ScoreAdd?.Invoke(10);
}
}
}
訂閱者:定義事件處理函數,訂閱事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameUI : MonoBehaviour
{
private BirdController m_BirdController;
int m_Score = 0;
// Use this for initialization
void Start()
{
m_BirdController = GameObject.Find("bird").GetComponent<BirdController>();
AddListener();
}
void OnDestroy()
{
RemoveListener();
}
// 訂閱
void AddListener()
{
m_BirdController.GameOver += OnGameOver;
m_BirdController.ScoreAdd += OnScoreAdd;
}
// 取關事件
void RemoveListener()
{
m_BirdController.GameOver -= OnGameOver;
m_BirdController.ScoreAdd -= OnScoreAdd;
}
void OnGameOver()
{
Debug.Log("你輸了");
}
void OnScoreAdd(int score)
{
m_Score += score;
Debug.Log("分數:" + m_Score);
}
}