How To Create And Use a Singleton in Unity?
Creating a Singleton in Unity is pretty simple. It basically works relatively similar to the procedure in vanilla C#. With the small difference that we basically don't have to worry about initialization (at least with MonoBehaviours).
First we create a static variable _instance. Additionally a property Instance. We use this later to access the singleton. Within the Awake method of the MonoBehaviour we then pass the reference to the instance of the class to the _instance variable.
using UnityEngine;
public class MyAwesomeClass : MonoBehaviour
{
private static MyAwesomeClass _instance;
// Add other class properties here...
public static MyAwesomeClass Instance
{
get {
if (_instance == null) {
Debug.LogError("MyAwesomeClass not instantiated.");
}
return _instance;
}
}
private void Awake()
{
_instance = this;
}
// Add other class methods here...
public void SomeMethod()
{
Debug.Log("It works.");
}
}
You can then access the methods and properties of the singleton very easily. The class is available in the global namespace.
MyAwesomeClass.Instance.SomeMethod();
Important: Be careful when you access the singleton. The Awake method runs relatively early within a game loop, but it can still happen that you try to access the instance too early. Of course, this does not happen with a pure C# solution.
There are no comments yet.