Created
January 8, 2019 07:01
-
-
Save MartinZikmund/344c3feafda5e431bb58e668737461af to your computer and use it in GitHub Desktop.
Singleton pattern for Unity3D
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
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour | |
{ | |
private static readonly Lazy<T> LazyInstance = new Lazy<T>(CreateSingleton); | |
public static T Instance => LazyInstance.Value; | |
private static T CreateSingleton() | |
{ | |
var ownerObject = new GameObject($"{typeof(T).Name} (singleton)"); | |
var instance = ownerObject.AddComponent<T>(); | |
DontDestroyOnLoad(ownerObject); | |
return instance; | |
} | |
} | |
//usage: | |
public class GameManager : Singleton<GameManager> | |
{ | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Worth mentioning:
This always creates a new object, placing Singletons deriving from this in a scene does nothing as they're never assigned as instances.
Singletons deriving from this should never be destroyed as they cannot be recreated.