BasicFantasy/Assets/Scripts/UnitySingleton.cs

94 lines
2.1 KiB
C#
Raw Permalink Normal View History

2023-09-28 18:21:45 +09:00
using UnityEngine;
namespace FirstVillain.Singleton
{
public class UnitySingleton<T> : MonoBehaviour where T : UnityEngine.Component
{
private static T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
string name = (typeof(T)).ToString();
_instance = new GameObject(name).AddComponent<T>();
}
return _instance;
}
}
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
else
{
_instance = this as T;
}
DontDestroyOnLoad(gameObject);
AwakeSingleton();
}
private void OnDestroy()
{
if (_instance == this)
{
_instance = null;
}
}
protected virtual void AwakeSingleton()
{ }
}
public class UnitySingletonOnce<T> : MonoBehaviour where T : UnityEngine.Component
{
private static T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
string name = (typeof(T)).ToString();
_instance = new GameObject(name).AddComponent<T>();
}
return _instance;
}
}
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
else
{
_instance = this as T;
}
AwakeSingleton();
}
private void OnDestroy()
{
if (_instance == this)
{
_instance = null;
}
}
protected virtual void AwakeSingleton()
{ }
}
}