71 lines
1.8 KiB
C#
71 lines
1.8 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
using UnityEngine.Windows;
|
|
|
|
/// <summary>
|
|
/// 事件中心
|
|
/// 1.字典 2.委托 3.观察者设计模式
|
|
/// </summary>
|
|
public class EventCenter : BaseManager<EventCenter>
|
|
{
|
|
//key ---事件名字(比如:怪物死亡,玩家死亡,通关 等等)
|
|
//value --- 对应 监听这个事件 对应的委托函数
|
|
private 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="action"></param>
|
|
public void RemoveEventListener(string name, UnityAction<object> action)
|
|
{
|
|
if(eventDic.ContainsKey(name))
|
|
{
|
|
eventDic[name] -= action;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 事件触发
|
|
/// </summary>
|
|
/// <param name="name">哪一个名字的事件触发了</param>
|
|
public void EvennTrigger(string name,object info)
|
|
{
|
|
if(eventDic.ContainsKey(name))
|
|
{
|
|
eventDic[name].Invoke(info);//有就触发事件
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 清空事件中心,主要用在场景切换时
|
|
/// </summary>
|
|
public void Clear()
|
|
{
|
|
eventDic.Clear();
|
|
}
|
|
}
|