49 lines
787 B
C#
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);
|
|
}
|
|
}
|
|
}
|
|
}
|