94 lines
2.1 KiB
C#
94 lines
2.1 KiB
C#
|
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()
|
|||
|
{ }
|
|||
|
}
|
|||
|
}
|