Quick Start
Create a class that inherits from Singleton.
public class SomeManager : Singleton<SomeManager>
{
public string HelloWorld = "Hello, World!";
}
Note
If you override Awake, you must call base.Awake() to ensure the singleton is initialized correctly.
That's it! You can now access the singleton from anywhere using SomeManager.Instance:
public class SomeOtherScript : MonoBehaviour
{
private void Start()
{
Debug.Log(SomeManager.Instance.HelloWorld);
}
}
The first time SomeManager.Instance is accessed, Singleton creates a new GameObject
named SomeManager if no instance already exists. If an instance is already present in
the scene, duplicate instances destroy their entire GameObject during Awake.
If you do not want Instance to create a new object automatically, inherit from
DontCreateNewSingleton
instead:
public class SomeManager : DontCreateNewSingleton<SomeManager>
{
public string HelloWorld = "Hello, World!";
}
Note
Again, if you override Awake, you must call base.Awake() to ensure the singleton is initialized correctly.
Unlike Singleton, DontCreateNewSingleton never creates a new instance automatically.
Check SomeManager.HasInstance before accessing SomeManager.Instance, or use SomeManager.TryGetInstance(out var instance),
if the singleton may not yet exist.