< Back to Game Dev, Unity

Making a singleton in Unity

What is a singleton? Basically, it’s code that can be used by everything else. This means you can share code between scenes in Unity. I usually use this to make sharable GUI styles. This is the basic set up:

public class singleton : MonoBehaviour {
    private static singleton instance;
    void Awake()
        instance = this;

Now you can specify variables and functions here that can be used by all other scripts. Here’s an example of a variable:

public GUIStyle styleFontAwesome;
instance.styleFontAwesome.font = (Font)Resources.Load("fontawesome-webfont");
instance.styleFontAwesome.normal.textColor = Color.white;
instance.styleFontAwesome.alignment = TextAnchor.MiddleCenter;

and an example of a function:

public static GUIStyle GetButtonStyle()
        return instance.styleFontAwesome;

In this example defaultButtonStyle(); is a private function in the script.

When you’re done, attach the script to the first scene of your game. Then in any script you can reuse the function like so:




Leave a Reply

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