What is a SINGLETON?

By definition, a singleton, at least in terms of object oriented programing, is a class that can have only one instance. That one instance is stored and referenced statically.

Here is the code necessary to create a simple singleton.

public class GameData
{
    #region Singleton

    private static GameData s_Instance;

    public static GameData instance
    {
        get
        {
            if (GameData.s_Instance == null)
                GameData.s_Instance = new GameData();
            return GameData.s_Instance;
        }
    }

    private GameData()
    {

    }

    #endregion

    // Your code here...

    public int hitPoints;

}

The code above creates a simple singleton class. Of course, if you are using this in Unity, you may want to use some of the standard Unity functions, such as FindObjectOfType. In this case, you will need to inherit from one of the standard Unity classes, such as ScriptableObject. These classes don’t like to be instantiated with new. Instead, they rely on function calls to create instances, so the code needs to be modified to accommodate that.

public class Localization : ScriptableObject
{
    #region Singleton

    private static Localization s_Instance;

    public static Localization instance
    {
        get
        {
            if (Localization.s_Instance == null)
                Localization.s_Instance = ScriptableObject.CreateInstance<Localization>();
            return Localization.s_Instance;
        }
    }

    #endregion

    // Your code here...

    public string language;
}

The region/endregion statements are not necessary. They are there simply to allow the whole region to be collapsed in the IDE. Add whatever other code you want to be part of the class, and you are ready to go.

In this example, you can refer to the string language from anywhere in your code by accessing the static instance of the Localization class as in the following example:

Localization.instance.language = "en-us";

Debug.Log(Localization.instance.language);

This code can be called from anywhere in your program, without the need to instantiate an object. The first time access Localization.instance, it is instantiated.

Leave a Reply

Your email address will not be published. Required fields are marked *