学习这个之前呢 ~
我们需要去学习c#中的委托Delegate 与事件Event 我的上一个文章就是委托Delegate的介绍 一定要看 多播委托!! (就是用的它)
提供网址 是菜鸟的 里面有委托与事件http://www.runoob.com/csharp/csharp-delegate.html
这里多说一句 其实Event 是一个打了标签的特殊的Delegate 这样使得只有在被定义的Class中才可以去调取Delegate 外部的类调取Delegate的时候,只能是使用两个功能,+ 加 与减 - 这就是在Delegate 前面加上定event 的原因 没有之一
首先我们假设一个创景 一直猫 与 3只老鼠 当猫来的时候老鼠就要逃跑 这样一个 观察-订阅者模式
第一步 我们先创建两个class 分别是 猫与老鼠
下面代码是猫
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Events;
public class Cat : MonoBehaviour {
//定义一个猫来的委托 当前面加上了event的话外部在new 这个class 的时候会出现 只能通过外部— + 的这两种使用方式 委托事件catCome只能再本class中调取
public event UnityAction catCome;//相当于发布消息
private string name;
private string color;
/// <summary>
/// 猫的构造函数 这只猫的属性
/// </summary>
/// <param name="name">毛的名字</param>
/// <param name="color">猫的颜色</param>
public Cat (string name,string color){
this.name = name;
this.color = color;
}
/// <summary>
/// 猫进屋(猫的状态发生了改变 也就是被观察者的状态发生了改变)
/// </summary>
public void CatComing(){
Debug.Log (color+ "色的猫"+name+"来了!,喵喵喵...");
if (catCome != null) {
catCome ();
}
}
}
是的~ 我们把委托事件放在猫的class里面 这样在猫来了的方法里面调取
下面是老鼠的Class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//老鼠类
public class Mouse : MonoBehaviour {
private string name;
private string color;
/// <summary>
/// 老鼠的构造函数 这只老鼠的属性
/// </summary>
/// <param name="name">老鼠的名字</param>
/// <param name="color">老鼠的颜色</param>
public Mouse (string name,string color,Cat cat){
this.name = name;
this.color = color;
//注册进去事件
cat.catCome += this.RunAway;//相当于订阅消息
}
/// <summary>
///老鼠逃跑方法
/// </summary>
public void RunAway(){
Debug.Log (color + "颜色的老鼠" + name + "看见猫来了,赶紧跑!");
}
}
在老鼠的class中我们会发现进行了 将老鼠逃跑的事件 通过这里注册到了cat 的委托事件中
下面是总控脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Observer : MonoBehaviour {
// Use this for initialization
void Start () {
Cat cat = new Cat ("加菲猫","黄色");
Mouse mouse1 = new Mouse ("米奇", "黑色",cat);
Mouse mouse2 = new Mouse ("唐老鸭", "红色",cat);
Mouse mouse3 = new Mouse ("奥特曼", "白色色",cat);
//添加注册事件! 但是这边每次调用都会出现 需要将创建出来的对象添加到委托函数中 所以我们可以进一步的进行游戏 将注册添加事件放在老鼠的构造方法中
// cat.catCome += mouse1.RunAway;
// cat.catCome += mouse2.RunAway;
// cat.catCome += mouse3.RunAway;
//调取猫来了的函数 在这里函数里面 再调取cat.catCome的委托事件 --也就是发布者 开始广播 猫来了
cat.CatComing ();
}
// Update is called once per frame
void Update () {
}
}