1.Monster
//触发事件
EventCenter.GetInstance().EventTrigger("MonsterDead",this);
2.Player
void Start()
{
EventCenter.GetInstance().AddEventListener("MonsterDead", MonsterDeadDo);
}
public void MonsterDeadDo(object info)
{
Debug.Log("玩家的奖励"+ (info as Monster).name);
}
void OnDestory()
{
EventCenter.GetInstance().RemoveEventListener("MonsterDead", MonsterDeadDo);
}
3.EventCenter
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// 事件中心 单例模式对象
/// 1.dictionary
/// 2.委托
/// 3.观察者设计模式
/// </summary>
public class EventCenter : Singleton<EventCenter>
{
//使用泛型委托传递怪物-蝙蝠等 具体敌人类型
public Dictionary<string, UnityAction<object>> eventDic = new Dictionary<string, UnityAction<object>>();
/// <summary>
/// 添加事件监听
/// </summary>
/// <param name="name">事件的名字</param>
/// <param name="action">准备用来处理事件的 委托函数</param>
public void AddEventListener(string name,UnityAction<object> action)
{
//判断事件中心是否有此 函数
if (eventDic.ContainsKey(name))
eventDic[name] += action;
//无
else
eventDic.Add(name, action);
}
/// <summary>
/// 执行函数
/// </summary>
/// <param name="name">事件名</param>
/// <param name="info">传递参数 具体怪物类型</param>
public void EventTrigger(string name,object info)
{
//判断触发中心是否有此 函数
if (eventDic.ContainsKey(name))
{
eventDic[name](info);
}
}
/// <summary>
/// 移除对应事件监听
/// </summary>
/// <param name="name">事件名</param>
/// <param name="action">委托函数</param>
public void RemoveEventListener(string name, UnityAction<object> action)
{
//判断事件中心是否有此 函数
if (eventDic.ContainsKey(name))
eventDic[name] -= action;
}
/// <summary>
/// 清空事件中心,主要用于场景切换
/// </summary>
public void Clear()
{
eventDic.Clear();
}
}