using System.Collections; using System.Collections.Generic; using UnityEngine; /* * Source: https://github.com/UnityCommunity/UnitySingleton * https://github.com/UnityCommunity/UnitySingleton/blob/master/Assets/Scripts/Singleton.cs * * Modifications: To prevent "Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)" * https://answers.unity.com/questions/1274772/some-objects-were-not-cleaned-up-when-closing-the-4.html */ public abstract class Singleton : MonoBehaviour where T : Component { #region Fields /// /// The instance. /// private static T instance; private static bool applicationIsQuitting = false; private static object _lock = new object(); #endregion #region Properties /// /// Gets the instance. /// /// The instance. public static T Instance { get { if (applicationIsQuitting) { return null; } lock (_lock) { if (instance == null) { instance = FindObjectOfType(); if (instance == null) { GameObject obj = new GameObject(); obj.name = typeof(T).Name; instance = obj.AddComponent(); } } } return instance; } } #endregion #region Methods /// /// Use this for initialization. /// protected virtual void Awake() { if (instance == null) { instance = this as T; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } protected void OnDestroy() { applicationIsQuitting = true; } #endregion }