ProjetAMJV_CR/Assets/Scripts/Singletons/Abstract/MonoBehaviourSingleton.cs
2025-01-20 21:05:28 +01:00

26 lines
No EOL
868 B
C#

using UnityEngine;
using System.Collections;
public class MonoBehaviourSingleton<T> : MonoBehaviour
where T : Component
{
private static T _instance;
public static T Instance {
get {
if (_instance == null) {
var objs = FindObjectsByType<T> (FindObjectsSortMode.None) as T[];
if (objs.Length > 0)
_instance = objs[0];
if (objs.Length > 1) {
Debug.LogError ("There is more than one " + typeof(T).Name + " in the scene.");
}
if (_instance == null) {
GameObject obj = new GameObject (typeof(T).Name);
obj.hideFlags = HideFlags.HideAndDontSave;
_instance = obj.AddComponent<T> ();
}
}
return _instance;
}
}
}