54 lines
1.5 KiB
C#
54 lines
1.5 KiB
C#
|
using UnityEngine;
|
|||
|
|
|||
|
namespace Assets.Scripts
|
|||
|
{
|
|||
|
public class SingletonMB<T> : MonoBehaviour where T : SingletonMB<T>
|
|||
|
{
|
|||
|
private static T instance;
|
|||
|
private static readonly object lockObject = new object();
|
|||
|
protected static bool Instantiated { get; private set; } = false;
|
|||
|
|
|||
|
public static T Instance
|
|||
|
{
|
|||
|
get
|
|||
|
{
|
|||
|
//lock (lockObject)
|
|||
|
//{
|
|||
|
if (instance == null)
|
|||
|
{
|
|||
|
instance = FindObjectOfType<T>();
|
|||
|
|
|||
|
if (instance == null)
|
|||
|
{
|
|||
|
GameObject obj = new GameObject();
|
|||
|
obj.name = typeof(T).Name;
|
|||
|
instance = obj.AddComponent<T>();
|
|||
|
Instantiated = true;
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
return instance;
|
|||
|
//}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
protected virtual void Awake()
|
|||
|
{
|
|||
|
Debug.Log($"{typeof(T).Name} singleton component Loaded");
|
|||
|
//lock (lockObject)
|
|||
|
//{
|
|||
|
if (instance == null)
|
|||
|
{
|
|||
|
instance = this as T;
|
|||
|
// DontDestroyOnLoad(gameObject);
|
|||
|
}
|
|||
|
else if (instance != this)
|
|||
|
{
|
|||
|
Destroy(gameObject);
|
|||
|
return;
|
|||
|
}
|
|||
|
Instantiated = true;
|
|||
|
//}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|