101 lines
2.5 KiB
Markdown
101 lines
2.5 KiB
Markdown
|
|
#灵感/代码缓存
|
|||
|
|
|
|||
|
|
## 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;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|