这个项目中慢慢尝试剥离出一个MicroFramework,做了两个泛型单例。
单例基类Singleton<T>,不需要手动挂载到GameObject上的脚本
\Unity\Assets\Scripts\MicroFramework\Singleton\Singleton.cs
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance = null;
public static T Ins
{
get
{
if (_instance == null)
{
GameObject go = new GameObject(typeof(T).Name,typeof(T));
_instance = go.GetComponent<T>();
}
return _instance;
}
}
protected void Awake()
{
// 注意&与&&区别
if (_instance != null & _instance == this)
return;
_instance = this as T;
}
void OnDestory()
{
if (_instance == this)
{
_instance = null;
}
}
}
SingletonMono<T>单例基类,需要手动挂载到GameObject上的脚本
\Unity\Assets\Scripts\MicroFramework\Singleton\SingletonMono.cs
using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance = null;
public static T Ins => _instance;
public virtual bool DontDestroy => false;
protected void Awake()
{
// 注意&与&&区别
if (_instance != null & _instance == this)
return;
_instance = this as T;
if(DontDestroy) DontDestroyOnLoad(gameObject);
}
void OnDestory()
{
if (_instance == this)
{
_instance = null;
}
}
}
Sigleton如何使用
public class UIFacade : Singleton<UIFacade>
{
// UI面板GameObject容器
public Dictionary<string, GameObject> currentScenePanelGoDict;
//UIPanel对象容器(当前场景状态下的UIPanel脚本对象)
public Dictionary<string, BasePanel> currentScenePanelDict;
public Transform canvas; // UIPanel放置的容器
}
SingletonMono如何使用
public partial class Sender : SingletonMono<Sender>
{
// 使用字典存储不同消息类型对应的处理方法
private Dictionary<ReciveType, MessageHandler> messageHandlers = new Dictionary<ReciveType, MessageHandler>();
private Dictionary<ReciveType, AddressableHandler> addressableHandlers = new Dictionary<ReciveType, AddressableHandler>();
public void Recive(ReciveType reciveType,IMessage message){
// 检查是否有注册过该消息类型的处理方法
if (messageHandlers.TryGetValue(reciveType, out var handler))
{
// 调用处理方法
handler.Invoke(message);
}
}
}