Last active
January 25, 2020 17:09
-
-
Save KarlRamstedt/8a9d8352903a22919d98ca93b79f73a4 to your computer and use it in GitHub Desktop.
Lazyloaded Singleton for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
/// <summary> | |
/// A Singleton that uses Lazy initialization. The superior option for persistent Singletons. | |
/// Thread-safe and efficient through the use of the Lazy class. | |
/// Can only be created once, so make sure it doesn't get destroyed. | |
/// ALWAYS creates a new object. Placing the Singleton in a scene does nothing. | |
/// </summary> | |
public abstract class LazySingleton<T> : MonoBehaviour where T : LazySingleton<T> { | |
static readonly Lazy<T> LazyInstance = new Lazy<T>(CreateSingleton); | |
public static T Inst => LazyInstance.Value; | |
static T CreateSingleton(){ | |
var obj = new GameObject("(Singleton)" + typeof(T).Name); | |
DontDestroyOnLoad(obj); | |
return obj.AddComponent<T>(); | |
} | |
#if UNITY_EDITOR | |
protected virtual void Reset(){ //Optional function that prevents manual instantiation | |
UnityEditor.EditorUtility.DisplayDialog("LazySingletons should not be manually instantiated", "Lazyloaded Singletons will load when first accessed. Instances that are part of scenes or prefabs do nothing.", "Ok"); | |
DestroyImmediate(this); | |
} | |
#endif | |
} | |
/// <summary> | |
/// A Singleton that uses Lazy initialization. The superior option for persistent Singletons. | |
/// Thread-safe and efficient through the use of the Lazy class. | |
/// Can only be created once, so make sure it doesn't get destroyed. | |
/// </summary> | |
public abstract class LazySOSingleton<T> : BehaviourEventListener where T : LazySOSingleton<T> { | |
static readonly Lazy<T> LazyInstance = new Lazy<T>(() => CreateInstance<T>()); | |
public static T Inst => LazyInstance.Value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment