using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventManger
{
/// <summary>
/// 存储所有的事件
/// </summary>
public static Dictionary<TypeEvent, DeleEvent> events = new Dictionary<TypeEvent, DeleEvent>();
/// <summary>
/// 添加事件
/// </summary>
/// <param name="type"></param>
/// <param name="handler"></param>
public static void Add(TypeEvent type, DeleEvent.EventHandler handler)
{
DeleEvent delEvent;
if (events.ContainsKey(type))
{
delEvent = events[type];
}
else
{
delEvent = new DeleEvent();
events[type] = delEvent;//events.add(type,delEvent)
}
delEvent.Add(handler);//添加事件
}
/// <summary>
/// 移除事件
/// </summary>
/// <param name="type">事件类型</param>
/// <param name="handler">监听函数</param>
public static void Remove(TypeEvent type, DeleEvent.EventHandler handler)
{
if (handler == null)
{
return;
}
if (!events.ContainsKey(type))
{
return;
}
DeleEvent del = events[type];
del.Remove(handler);
}
/// <summary>
/// 触发事件 传递数据
/// </summary>
/// <param name="type">事件类型</param>
/// <param name="data">数据</param>
public static void SendEvent(TypeEvent type, object data)
{
if (!events.ContainsKey(type))
{
return;
}
//创建事件数据包
EventMessage mes = new EventMessage();
mes.type = type;
mes.data = data;
DeleEvent del = events[type];
del.Handler(mes);
}
}
///
/// 事件类
///
public class DeleEvent
{
/// <summary>
/// 定义委托
/// </summary>
/// <param name="data"></param>
public delegate void EventHandler(EventMessage data);
/// <summary>
/// 事件
/// </summary>
public event EventHandler handler;
/// <summary>
/// 触发监听事件,也是具体处理和分发事件的地方
/// </summary>
/// <param name="data"></param>
public void Handler(EventMessage data)
{
if (handler != null)
{
handler(data);
}
}
/// <summary>
/// 添加事件
/// </summary>
/// <param name="removeHandler"></param>
public void Add(EventHandler removeHandler)
{
handler += removeHandler;
}
/// <summary>
/// 删除事件
/// </summary>
/// <param name="removeHandler"></param>
public void Remove(EventHandler removeHandler)
{
if (handler != null)
{
handler -= removeHandler;
}
}
}
///
/// 事件类型(根据实际需求)
///
public enum TypeEvent
{
登录, 注册,升级
}
///
/// 事件数据
///
public class EventMessage
{
/// <summary>
/// 事件类型
/// </summary>
public TypeEvent type;
/// <summary>
/// 数据
/// </summary>
public object data;
}