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

56 lines
940 B
C#

using System;
using UnityEngine;
namespace BitStrap
{
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
return GetInstance(true);
}
}
public static void RequireInstance(Action<T> callback)
{
T val = GetInstance(false);
if (val != null && callback != null)
{
callback(val);
}
}
public static T GetInstance(bool warnIfNotFound)
{
if (instance == null)
{
instance = UnityEngine.Object.FindObjectOfType<T>();
if (instance == null && warnIfNotFound)
{
OnInstanceNotFound();
}
}
return instance;
}
protected void ForceSingletonInstance()
{
instance = this as T;
}
protected virtual void OnDestroy()
{
instance = (T)null;
}
private static void OnInstanceNotFound()
{
Debug.LogWarningFormat("Didn't find a object of type {0}!", typeof(T).Name);
}
}
}