obsidian/笔记文件/2.笔记/单例模式.md

101 lines
2.5 KiB
Markdown
Raw Normal View History

2025-03-26 00:02:56 +08:00
#灵感/代码缓存
## MonoSingleton
``` cs
/****************************************************
文件MonoSingleton.cs
作者HuskyT
邮箱1005240602@qq.com
日期2021/7/3 13:33:10
功能Mono单例
*****************************************************/
using UnityEngine;
namespace HTFramework.Utility
{
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
static T mInstance;
public static T Instance
{
get
{
if (mInstance == null)
{
//根据类型 T 搜索实例
T[] instanceArray = FindObjectsOfType<T>();
string typeName = typeof(T).Name;
//场景中 无实例
if (instanceArray == null || instanceArray.Length == 0)
{
//根据类型名搜索场景中 GameObject
GameObject instanceObj = GameObject.Find(typeName);
if (instanceObj == null) //无同名 GameObject
{
instanceObj = new GameObject(typeName);
DontDestroyOnLoad(instanceObj); //切换场景 单例不销毁
}
mInstance = instanceObj.AddComponent<T>(); //添加实例
}
//场景中 有一个实例
else if (instanceArray.Length == 1)
{
mInstance = instanceArray[0];
}
//场景中 有多个实例
else
{
mInstance = instanceArray[0];
}
}
return mInstance;
}
}
}
}
```
Singleton
``` cs
/****************************************************
文件Singleton.cs
作者HuskyT
邮箱1005240602@qq.com
日期2021/07/03 13:19:19
功能:普通单例模板
*****************************************************/
namespace HTFramework.Utility
{
public class Singleton<T> where T : class, new()
{
static T mInstance = null;
public static T Instance
{
get
{
if (mInstance == null)
{
mInstance = new T();
}
return mInstance;
}
}
public static void ResetStatic()
{
mInstance = null;
}
}
}
```