在這個例子中運(yùn)用了委托事件機(jī)制
講述了事件和委托的區(qū)別
最大的區(qū)別是:
事件是特殊的受限的委托,事件只能在類內(nèi)部調(diào)用,不能在類的外部調(diào)用起到保護(hù)作用,可以在類的外部通過+=添加事件
1、首先是Cat的類代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Cat {
private string name;
private string color;
public event Action catCome;//事件不能在類的外部觸發(fā),只能在類的內(nèi)部觸發(fā)。 委托都可以觸發(fā)。
public Cat(string name,string color)
{
this.name=name;
this.color=color;
}
public void CatComing()
{
Debug.Log(color+"的貓"+name+"過來了");
if(catCome!=null)
{
catCome();
}
}
}
2、其次是Mouse的類代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mouse {
private string name;
private string color;
public Mouse(string name,string color,Cat cat)
{
this.name=name;
this.color=color;
cat.catCome+=RunAway;
}
public void RunAway()
{
Debug.Log(color +"的老鼠"+name+"說貓來了");
}
}
3、最后是Main方法代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
// Use this for initialization
void Start () {
Cat cat=new Cat("加菲貓","黃色");
Mouse mouse1=new Mouse("米奇","黑色",cat);
Mouse mouse2=new Mouse("airu","白色",cat);
cat.CatComing();
}
// Update is called once per frame
void Update () {
}
}