Singleton

Singleton allows us to create one, single instance of an object. This approach let us communicate with singleton’s class elements more easily. We can create a singleton for a class that we are sure that won’t be instantiated more than once.

A good example for a singleton will be a GameManager script.

 

public class GameManager : MonoBehaviour
{
    public static GameManager instance = null;
    void Awake()
    {
        if(instance == null)
        {
            instance = this;
            // DontDestryOnLoad(gameObject);
        }
        else if(instance != this)
        {
            Destroy(gameObject);
        }
    }

    public void ShowTheMessage()
    {
        print("Calling a function from GameManager singleton instance");
    }
}

Now, in easy way, we can call the ShowTheMessage() method from other scripts:

    void Start()
    {
        GameManager.instance.ShowTheMessage();
    }