Unity_内部消息机制

来源:互联网 发布:改造农村老房子 知乎 编辑:程序博客网 时间:2024/06/05 14:14
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;        }    }}

原创粉丝点击