using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using GameType;
public class Messenger{
private static Dictionary<ClickType, Delegate> mDict = new Dictionary<ClickType, Delegate>();
private static bool OnAddListener(ClickType type,Delegate handler)
{
if (!mDict.ContainsKey(type))
{
mDict.Add(type, null);
}
Delegate d = mDict[type];
if (d != null && d.GetType()!=handler.GetType())
{
return false;
}
return true;
}
private static bool OnRemoveListener(ClickType type,Delegate handler)
{
if (mDict.ContainsKey(type))
{
Delegate d = mDict[type];
if (d==null)
{
return false;
}
else if (d.GetType()!=handler.GetType())
{
return false;
}
}
else
{
return false;
}
return true;
}
public static void AddListener(ClickType type,Callback handler)
{
if (!OnAddListener(type,handler))
{
return;
}
mDict[type] = (Callback)mDict[type] + handler;
}
public static void AddListener<T>(ClickType type,Callback<T> handler)
{
if (!OnAddListener(type,handler))
{
return;
}
mDict[type] = (Callback<T>)mDict[type] + handler;
}
public static void RemoveListener(ClickType type,Callback handler)
{
if (!OnRemoveListener(type,handler))
{
return;
}
mDict[type] = (Callback)mDict[type] - handler;
if (mDict[type]==null)
{
mDict.Remove(type);
}
}
public static void RemoveListener<T>(ClickType type,Callback<T> handler)
{
if (!OnRemoveListener(type, handler))
{
return;
}
mDict[type] = (Callback<T>)mDict[type] - handler;
if (mDict[type] == null)
{
mDict.Remove(type);
}
}
public static void Broadcast(ClickType type)
{
if (!mDict.ContainsKey(type))
{
return;
}
Delegate d;
if(mDict.TryGetValue(type, out d))
{
Callback callback = d as Callback;
if (callback != null)
callback();
else
return;
}
}
public static void Broadcast<T>(ClickType type,T arg)
{
if (!mDict.ContainsKey(type))
{
return;
}
Delegate d;
if (mDict.TryGetValue(type, out d))
{
Callback<T> callback = d as Callback<T>;
if (callback != null)
callback(arg);
else
return;
}
}
}
Unity_内部消息机制
最新推荐文章于 2021-06-22 08:07:18 发布