using UnityEngine; using System.Collections; namespace Fungus { /// /// Fungus manager singleton. Manages access to all Fungus singletons in a consistent manner. /// [RequireComponent(typeof(CameraManager))] [RequireComponent(typeof(MusicManager))] [RequireComponent(typeof(SaveManager))] public sealed class FungusManager : MonoBehaviour { static FungusManager instance; static bool applicationIsQuitting = false; static object _lock = new object(); void Awake() { CameraManager = GetComponent(); MusicManager = GetComponent(); SaveManager = GetComponent(); } /// /// When Unity quits, it destroys objects in a random order. /// In principle, a Singleton is only destroyed when application quits. /// If any script calls Instance after it have been destroyed, /// it will create a buggy ghost object that will stay on the Editor scene /// even after stopping playing the Application. Really bad! /// So, this was made to be sure we're not creating that buggy ghost object. /// void OnDestroy () { applicationIsQuitting = true; } #region Public methods /// /// Gets the camera manager singleton instance. /// public CameraManager CameraManager { get; private set; } /// /// Gets the music manager singleton instance. /// public MusicManager MusicManager { get; private set; } /// /// Gets the save manager singleton instance. /// public SaveManager SaveManager { get; private set; } /// /// Gets the FungusManager singleton instance. /// public static FungusManager Instance { get { if (applicationIsQuitting) { Debug.LogWarning("FungusManager.Instance() was called while application is quitting. Returning null instead."); return null; } lock (_lock) { if (instance == null) { var go = new GameObject(); go.name = "FungusManager"; DontDestroyOnLoad(go); instance = go.AddComponent(); } return instance; } } } #endregion } }