// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) 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))] #if UNITY_5_3_OR_NEWER [RequireComponent(typeof(SaveManager))] #endif public sealed class FungusManager : MonoBehaviour { static FungusManager instance; static bool applicationIsQuitting = false; static object _lock = new object(); void Awake() { CameraManager = GetComponent(); MusicManager = GetComponent(); #if UNITY_5_3_OR_NEWER SaveManager = GetComponent(); #endif } /// /// 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; } #if UNITY_5_3_OR_NEWER /// /// Gets the save manager singleton instance. /// public SaveManager SaveManager { get; private set; } #endif /// /// 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 } }