Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(197评价)
价格: 4431.00元
关于观察者模式在Unity中遇到的问题
PublicFaith发起了问答2018-03-22
1
回复
393
浏览

看了猫捉老鼠案例 想直接在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 () {
		
	}
}

大致上就是在最后输出的时候有问题

所有回复
  • siki 2018-03-23
    ActionMouse 

    ActionMouse继承自了Mono,那么她就是一个组件,Unity中的组件我们不能自己new,得把它挂在游戏物体身上,让unity去new它的对象 

    还有-5条回复,点击查看
    你还没有登录,请先登录注册
发表回复
你还没有登录,请先 登录或 注册!