Files
test/Assets/PerfectWorld/Scripts/Common/MonoSingleton.cs
2026-02-27 20:46:21 +07:00

42 lines
1.2 KiB
C#

using UnityEngine;
namespace BrewMonster
{
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindFirstObjectByType<T>();
if (_instance == null)
{
BMLogger.LogError($"MonoSingleton<{typeof(T).Name}>: No instance found, creating new one");
GameObject obj = new GameObject(typeof(T).Name);
_instance = obj.AddComponent<T>();
}
}
return _instance;
}
}
protected virtual void Awake()
{
_instance = this as T;
Initialize();
}
protected virtual void OnDestroy()
{
_instance = null;
}
/// <summary>Override this method to initialize the singleton</summary>
protected virtual void Initialize()
{
}
}
}