Files
2026-02-21 16:45:37 +08:00

49 lines
787 B
C#

using System;
using UnityEngine;
namespace Moonlit.Utils
{
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _Instance;
public static bool IsInitialized
{
get
{
return _Instance != null;
}
}
public static T Instance
{
get
{
TryCreate();
return _Instance;
}
}
public static void TryCreate()
{
if (!IsInitialized)
{
T[] array = UnityEngine.Object.FindObjectsOfType<T>();
if (array != null && array.Length != 1)
{
throw new Exception(typeof(T).Name + ": not found on scene!");
}
_Instance = array[0];
}
}
public static void DestroyInstance()
{
if (IsInitialized && _Instance != null)
{
UnityEngine.Object.Destroy(_Instance.gameObject);
}
}
}
}