using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Plugins.Countly { public class MonoSingleton : MonoBehaviour where T : MonoSingleton { private static T m_Instance; private static bool _isInitialized; public static T Instance { get { // Instance requiered for the first time, we look for it if (m_Instance == null) { m_Instance = FindObjectOfType(typeof(T)) as T; // Object not found, we create a temporary one if (m_Instance == null) { Debug.LogWarning("No instance of " + typeof(T) + ", a temporary one is created."); isTemporaryInstance = true; m_Instance = new GameObject("Singleton of " + typeof(T).Name, typeof(T)) .GetComponent(); // Problem during the creation, this should not happen if (m_Instance == null) Debug.LogError("Problem during the creation of " + typeof(T)); } if (!_isInitialized) _isInitialized = true; // m_Instance.Init(); } return m_Instance; } } public static bool isTemporaryInstance { private set; get; } // If no other monobehaviour request the instance in an awake function // executing before this one, no need to search the object. private void Awake() { if (m_Instance == null) { m_Instance = this as T; } else if (m_Instance != this) { Debug.LogError("Another instance of " + GetType() + " is already exist! Destroying self..."); DestroyImmediate(this); return; } if (!_isInitialized) { DontDestroyOnLoad(gameObject); _isInitialized = true; m_Instance.Init(); } } /// /// This function is called when the instance is used the first time /// Put all the initializations you need here, as you would do in Awake /// protected virtual void Init() { } /// Make sure the instance isn't referenced anymore when the user quit, just in case. protected virtual void OnApplicationQuit() { m_Instance = null; } } }