Making a singleton in Unity

Posted on

in

,

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()
    {
        instance.defaultButtonStyle();
        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:

singleton.GetButtonStyle();

 

 

Leave a Reply

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

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930