Singleton design pattern in unity - technoob

Singleton design pattern is one of the simplest and widely used design patterns. Singleton simply means that the class cannot be instantiated and there should be only one instance of that class. The singleton instance is created using the static keyword as we need to access it without creating a new instance. 

singleton in unity engine


Creating singletons is a bit different from language to language. But the concept is still the same. In Unity creating a singleton is a bit different from other languages as there are scenes and we need to make sure our instance gonna persist in between every scene. How we create a singleton in Unity is pretty easy.


public class ManagerClass
{
    public static ManagerClass instance;

    void Awake()
    {
        if(instance == null)
           instance = this;
        else if(instance != this)
           Destroy(gameObject);
        DontDestroyOnLoad(gameObject);
    }
}

We create a variable of the class called instance. In the awake method, we check if the instance is null and if it is then we set the instance. If there's another instance already, then we simply destroy the game object. "DontDestroyOnLoad" method takes one argument of type game object and Unity Engine doesn't destroy that game object when changing the scenes.


It is always a good practice to create singletons only for managers in Unity. When we access a non-static variable in a static method in this class, we can simply access it using 'instance'.


Comments