初识发布与订阅模型
完成一下课堂的实验:Garen跳到最高点时发出消息“JumpTopPoint”,发出通知消息,订阅者接收到消息,做出相应反馈。
放个代码:
//发布
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GarenEvent : MonoBehaviour {
public delegate void GarenSubject(GameObject self, string message); //定义回调函数类型
public static event GarenSubject OnGarenSubjectNotify; //定义subject
void JumpTopPoint()
{
Debug.Log("Jump to the top point!");
if (OnGarenSubjectNotify != null)
OnGarenSubjectNotify(this.gameObject, "AtTop"); //发出通知,事件由谁处理, 如何处理都不需要知道
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// JumpTopPoint();
}
}
//订阅,处理
public class SceneController : MonoBehaviour {
void ReceiveMessage(Object sender, string info)
{
Debug.Log("Has Received");
}
void OnEnable()
{
GarenEvent.OnGarenSubjectNotify += ReceiveMessage; //订阅
}
void OnDisable()
{
GarenEvent.OnGarenSubjectNotify -= ReceiveMessage; //取消
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
}
把这两个代码文件都挂在Garen上就可以了,结果大概是这个样子:当Garen跳到最高点的时候(这里需要在Animation窗口手动添加Animation Event,在最高点key frame右键添加Event,Function就写JumpTopPoint,如果不手动添加Event,是不会有任何反应的,因为代码里并没有调用JumpTopPoint();),会在控制台显示
本周作业
游戏设计要求:
创建一个地图和若干巡逻兵(使用动画);
每个巡逻兵走一个3~5个边的凸多边型,位置数据是相对地址。即每次确定下一个目标位置,用自己当前位置为原点计算;
巡逻兵碰撞到障碍物,则会自动选下一个点为目标;
巡逻兵在设定范围内感知到玩家,会自动追击玩家;