在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挂在摄像机上。运行场景
这里写图片描述

点击按妞:
这里写图片描述

通过事件机制可以将对象之间的互相依赖降低到最低,这便是松耦合的威力。而观察者模式的意义同样在于此,它是一种让主题和观察者之间实现松耦合的设计模式:当两个对象之间松耦合,虽然不清楚彼此的细节,但是他们仍然可以交互。在观察者设计模式中,主题只需要了解观察者是否实现了和确定的方法原型想匹配的回调方法,而无须了解观察者的具体类是什么。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐