Files
Studio/Assets/Scripts/Studio/Core/UnitySingleton.cs
2025-04-03 11:41:16 +09:00

80 lines
2.2 KiB
C#

using UnityEngine;
using System.Collections;
namespace XED.Core
{
public abstract class UnitySingleton<T> : UnityEngine.MonoBehaviour where T : UnitySingleton<T>
{
private static T _instance;
private static object _lock = new object();
protected static bool applicationIsQuitting = false;
public static bool IsApplicationQuitting
{
get
{
return applicationIsQuitting;
}
}
public static T instance
{
get
{
if (applicationIsQuitting)
{
Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
"' already destroyed on application quit." +
" Won't create again - returning null.");
return null;
}
lock (_lock)
{
if (_instance == null)
{
_instance = FindFirstObjectByType(typeof(T)) as T;
if (_instance == null)
{
GameObject singleton = new GameObject(typeof(T).Name);
_instance = singleton.AddComponent<T>();
_instance.Init();
_instance.name = typeof(T).ToString();
DontDestroyOnLoad(_instance.gameObject);
}
}
return _instance;
}
}
}
void Awake()
{
lock (_lock)
{
if (_instance == null)
{
_instance = this as T;
}
else if (_instance != this)
{
Debug.LogError(this.name + " Destroy !!!");
Destroy(this.gameObject);
return;
}
}
}
protected virtual void Init()
{
}
protected virtual void OnApplicationQuit()
{
#if UNITY_EDITOR
#else
applicationIsQuitting = true;
#endif
}
}
}