Skip to content

Instantly share code, notes, and snippets.

@MartinZikmund
Created January 8, 2019 07:01
Show Gist options
  • Save MartinZikmund/344c3feafda5e431bb58e668737461af to your computer and use it in GitHub Desktop.
Save MartinZikmund/344c3feafda5e431bb58e668737461af to your computer and use it in GitHub Desktop.
Singleton pattern for Unity3D
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>
{
...
}
@KarlRamstedt
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment