Unity3D Tutorials: Singleton

Hi and welcome to the second tutorial about Unity3D!

This time we will be learning about Singletons, this little pattern may help you in dealing with some common issues you might find in game development.

Remember that those tutorials expects you to have some kind of programming experience.

What is a Singleton?

A Singleton is a design pattern that restricts the instantiation of a class to a single instance. This mean that at any given time you can expect the object to be the same one, and no other to exist.

Why a Singleton?

While a lot of people will turn their nose toward it and label it ‘evil’, I find that Singletons are very useful in the environment of Unity3D.

Mostly they help solve a big issue of communicating between assets and runtime objects, which is aggravated by the scene pattern.

For example, let’s say you have a game with elemental damage, and all damage of the same element displays the same effect on the screen.

You will probably want to store the effects in the same place, it might be an scriptable object or a simple prefab with a class.
But in any case you will need to eventually allow that information to be available somewhere, so you can actually spawn the effect.

It doesn’t matter if you want to directly allow access to the class that manages the effects or if you have another class that manages a bigger portion, for example combat, that wants to use it, eventually there will be a single point of contact between your assets in your project and objects actually in your scene.

And that one will probably be a singleton, let’s think, do you really need multiple instances of a class that regardless of any situation will always do the same thing and have the same info?

What about Static classes?

I won’t enter much about static classes since they are not the focus of this tutorial, but if you know about them, chances are they came to your mind in the last question.

So why not? It’s because static classes cannot be added as components to gameobjects in Unity3D, so they cannot become your point of contact between runtime and your assets.

How do I make a Singleton?

So let’s use our effect example to make a Singleton.

This is how it will look like in Unity3D.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExampleElementalEffects : MonoBehaviour {

    public static ExampleElementalEffects instance;

    public GameObject waterEffect;
    public GameObject windEffect;
    public GameObject earthEffect;
    public GameObject fireEffect;

    public static ExampleElementalEffects GetInstance() {
        return instance;
    }

    private void Awake() {
        if (!Application.isPlaying) {
            return;
        }

        if (instance != null) {
            Destroy(gameObject);
            return;
        }

        instance = this;

        DontDestroyOnLoad(gameObject);
    }

    public void SpawnEffectAt(Vector3 fxPos) {

    }
}

And this is the script.

The first line inside the class declaration public static ExampleElementalEffects instance; will provide a way to access the instance of this class from anywhere, just by doing ExampleElementalEffects.instance.

The GetInstance() is another example of how to do it, by doing ExampleElementalEffects.GetInstance() you will also get the instance of this class.

Then we have the declaration of the gameobjects used for the elemental effects, they are public to allow you to set them in the editor.

The Awake is used to enforce the Singleton pattern, the first condition checks if the object is being instanced while the game is running, while this has no effect in this script I left as an example if you want to mess with editor running scripts.

The second condition checks if an instance of this class already exists, if it does we simply destroy this one and returns, canceling anything else this function might do.

Lastly we set the instance field to this instance and calls DontDestroyOnLoad, assuring this object will not be destroyed in scene changes.

The last method does nothing in our example, but I just put to illustrate that this class can show an effect somewhere.

Take care when using it

While Singletons can help solve some problems presented in Unity3D, do try to think if they are really necessary in what you are wanting to achieve.
A Singleton will tie down your code and might make things more cumbersome later on.

In a Nutshell!

– Singletons help you maintain a controlled environment where you assure only one instance of a given class can exist at the same time.
– They are very useful in Unity3D due to some design choices of the engine.
– Think if they are what you really need for your current solution.
– Some other use cases might be log files and low level hardware access.

Thanks again for reading and I hope it was of help!

Liked it? Take a second to support TinyBird Games on Patreon!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.