using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Beyond { public abstract class AutoSingleton : MonoBehaviour where T : AutoSingleton { private static T s_instance; public static T Instance { get { if (s_instance) { return s_instance; } else { var inst = FindObjectOfType(); if (inst != null) { s_instance = inst; return s_instance; } else { var go = new GameObject("_" + typeof (T).Name); go.AddComponent(); // _instance set by Awake() constructor } } return s_instance; } } protected void OnDestroy() { if (s_instance == this) s_instance = null; } protected virtual void Awake() { if (s_instance == null) { s_instance = (T)this; } else { Debug.LogError("Multiple instances of singleton :"+gameObject.name); } } } }