看了猫捉老鼠案例 想直接在Unity中尝试使用
先贴下代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActionMouse : MonoBehaviour {
string mouseName;
string mouseColor
{
get;
set;
}
public ActionMouse(string name,string color,ActionCat cat)
{
this.mouseName = name;
this.mouseColor = color;
cat.catShoutEvent += this.MouseRun;
}
public void MouseRun()
{
//Method1... ... ...
//Method2... ... ...
//Method2... ... ...
print("The"+ mouseColor +"mouse named" +name+ "said : The Cat is coming,everybody run!");
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActionCat : MonoBehaviour {
public delegate void CatShoutEventHandler();
public event CatShoutEventHandler catShoutEvent;
string catName;
string catColor;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public ActionCat(string name , string color)
{
this.catName = name;
this.catColor = color;
}
/// <summary>
/// 猫进屋(猫的状态发生改变)(被观察者的状态发生改变)
/// </summary>
public void CatShout()
{
print("There are a " + catColor + "and call" + catName + "cat coming~~");
if(catShoutEvent != null)
{
catShoutEvent();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActionManage : MonoBehaviour {
ActionCat cat;
ActionMouse mouse1;
// Use this for initialization
void Start () {
cat = new ActionCat("cTest1", "blue");
mouse1 = new ActionMouse("mTest1", "yellow", cat);
//cat.catShoutEvent += mouse1.MouseRun;
cat.CatShout();
}
// Update is called once per frame
void Update () {
}
}
大致上就是在最后输出的时候有问题
ActionMouse
ActionMouse继承自了Mono,那么她就是一个组件,Unity中的组件我们不能自己new,得把它挂在游戏物体身上,让unity去new它的对象