Files
plugin-library/Assets/00.StaryEvo/Runtime/Singleton.cs
2025-03-31 11:16:52 +08:00

85 lines
2.1 KiB
C#

using System;
using System.Reflection;
using UnityEngine;
namespace Stary.Evo
{
public class Singleton<T> where T : class
{
public static T Instance
{
get
{
if (mInstance == null)
{
// 通过反射获取构造
var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
// 获取无参非 public 的构造
var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
if (ctor == null)
{
throw new Exception("Non-Public Constructor() not found in " + typeof(T));
}
mInstance = ctor.Invoke(null) as T;
}
return mInstance;
}
}
private static T mInstance;
}
/// <summary>
/// 单例基类
/// </summary>
/// <typeparam name="T"></typeparam>
public class MonoSingleton<T>: MonoBehaviour where T: MonoBehaviour
{
private static T mInstance;
public static T Instance
{
get {
if (mInstance == null)
{
T t = GameObject.FindObjectOfType<T>();
if (t)
{
mInstance = t;
}
else
{
GameObject go = new GameObject(typeof(T).Name);
mInstance = go.AddComponent<T>();
}
return mInstance;
}
return mInstance;
}
}
}
public class DoNotDestroy : MonoBehaviour
{
public static DoNotDestroy Instance;
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
}