1. 程式人生 > >unity學習——事件機制(觀察者模式)

unity學習——事件機制(觀察者模式)

在C#中的事件機制便是以委託作為基礎的。下面我們來做一個小例子:場景中一個按妞,點選按妞,通過攝像機上的指令碼來列印一句話。
1.定義委託型別,確定回撥方法原型。
public delegate void buttonDelegate();
2.定義事件成員。
public event buttonDelegate buttonEvent;
3.定義觸發事件的方法。
private void Click()
{
Debug.Log(“按妞被點選”);
if (buttonEvent != null)
buttonEvent();
}
4.定義事件的觀察者。
eventR類
5.實現觀察者模式

!!!eventSub類

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class eventSub : MonoBehaviour {
    public Button button;
    public delegate void buttonDelegate();
    public event buttonDelegate buttonEvent;
  protected virtual void Onbutton
() { } // Use this for initialization private void Click() { Debug.Log("按妞被點選"); if (buttonEvent != null) buttonEvent(); } private void Start() { button.onClick.AddListener(Click); } // Update is called once per frame void
Update () { } }

eventR類

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class eventR : MonoBehaviour {
    public eventSub sub;

    private void AddListener()
    {
        this.sub.buttonEvent += new eventSub.buttonDelegate(this.Click);
        // Use this for initialization

    }
    private void RemoveListener()
    {
        this.sub.buttonEvent-=new eventSub.buttonDelegate(this.Click);
    }

    private void Click()
    {
        Debug.Log("然後。。。。。");
    }
    private void Start()
    {

        this.AddListener();
    }
}

將eventSub類掛在button上,eventR掛在攝像機上。執行場景
這裡寫圖片描述

點選按妞:
這裡寫圖片描述

通過事件機制可以將物件之間的互相依賴降低到最低,這便是鬆耦合的威力。而觀察者模式的意義同樣在於此,它是一種讓主題和觀察者之間實現鬆耦合的設計模式:當兩個物件之間鬆耦合,雖然不清楚彼此的細節,但是他們仍然可以互動。在觀察者設計模式中,主題只需要瞭解觀察者是否實現了和確定的方法原型想匹配的回撥方法,而無須瞭解觀察者的具體類是什麼。