using System;
using System.Collections.Generic;
public class MessageManager
{
static MessageManager mInstance;
public static MessageManager Instance
{
get
{
return mInstance ??= new MessageManager();
}
}
Dictionary<string, Action<object[]>> mMessageDict = new Dictionary<string, Action<object[]>>(32);
Dictionary<string, object[]> mDispatchCacheDict = new Dictionary<string, object[]>(16);
private MessageManager()
{
}
public void Suvscribe(string MessageManager, Action<object[]> action)
{
Action<object[]> value = null;
if (mMessageDict.TryGetValue(MessageManager, out value))
{
value += action;
mMessageDict[MessageManager] = value;
}
else
{
mMessageDict.Add(MessageManager, action);
}
}
public void Unsubscribe(string message)
{
mMessageDict.Remove(message);
}
public void Dispatch(string message, object[] args = null, bool addToCache = false)
{
if (addToCache)
{
mDispatchCacheDict[message] = args;
}
else
{
Action<object[]> value = null;
if (mMessageDict.TryGetValue(message, out value))
value(args);
}
}
public void ProcessDispatchCache(string message)
{
object[] value = null;
if (mDispatchCacheDict.TryGetValue(message,out value))
{
Dispatch(message, value);
mDispatchCacheDict.Remove(message);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : SingletonBase<GameManager>
{
Action<object[]> act;
protected override void Awake()
{
base.Awake();
DontDestroyOnLoad(this);
act = SuvFunc;
MessageManager.Instance.Suvscribe("abc", act);
MessageManager.Instance.Dispatch("abc");
}
private void SuvFunc(object[] obj)
{
Debug.Log("TestSuv");
}
protected override void OnDestroy()
{
base.OnDestroy();
MessageManager.Instance.Unsubscribe("abc");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonBase<T> : MonoBehaviour where T : SingletonBase<T>
{
private static T instance;
public static T Instance
{
get { return instance; }
}
protected virtual void Awake()
{
if (instance != null)
Destroy(gameObject);
else
instance = (T)this;
}
public static bool IsInitalized
{
get { return instance != null; }
}
protected virtual void OnDestroy()
{
if (instance == this)
{
instance = null;
}
}
}
|