unity学习——事件机制(观察者模式)

本文通过Unity实例详细介绍了C#中的事件机制及如何使用委托实现观察者模式,以此来降低对象间的耦合度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值