Projet-IA-Madelaine/Scripts/SingletonMB.cs

54 lines
1.5 KiB
C#
Raw Normal View History

2024-06-12 21:03:42 +02:00
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;
//}
}
}
}