diff --git a/Assets/Scripts/SceneSingleton.cs b/Assets/Scripts/SceneSingleton.cs new file mode 100644 index 0000000..d29e8e5 --- /dev/null +++ b/Assets/Scripts/SceneSingleton.cs @@ -0,0 +1,67 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +// "Scene Singleton Pattern" or "Local Singleton Pattern" +// It differs from the traditional "Global singleton pattern", +// The purpose of "Scene Singleton Pattern" is to ensure that there is only one instance of the class in a given scene, but it does not require that instance to persist across scenes. +// This pattern is useful when you need to manage certain assets or features in a single scene, but you don't want those assets or features to remain present when the scene is switched. + +public abstract class SceneSingleton : MonoBehaviour where T : Component +{ + + #region Fields + + /// + /// The instance. + /// + private static T instance; + + #endregion + + #region Properties + + /// + /// Gets the instance. + /// + /// The instance. + public static T Instance + { + get + { + 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; + } + else + { + Destroy(gameObject); + } + } + + #endregion + +} diff --git a/Assets/Scripts/SceneSingleton.cs.meta b/Assets/Scripts/SceneSingleton.cs.meta new file mode 100644 index 0000000..49ba90c --- /dev/null +++ b/Assets/Scripts/SceneSingleton.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 122ad7d0387233a4cb949b8c621bd8f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: