Unity and Singleton

Tulenber 21 February, 2020 ⸱ Beginner ⸱ 2 min ⸱

Singleton, neat, cola back.

Certainly, patterns are one of the most important topics not only in game development but also in programming in general. It is unlikely that you will not be asked a question about patterns during an interview on a programmer position, and there is a strong feeling that Singleton mentioned first in 80% of them. =)
There are millions of articles about patterns, so if you feel a lack of theoretical knowledge about it, read this book or this concrete chapter about Singleton.

Implementation

Singleton has almost the same count of implementations as articles about it, so that one more used here:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    private static T instance;

    public static T Instance
    {
        get => instance;
    }

    public static bool IsInstantiated
    {
        get => instance != null;
    }

    protected virtual void Awake()
    {
        if (instance != null)
        {
            Debug.LogError("[Singleton] Trying to instantiate a second instance of singleton class.");
        }
        else
        {
            instance = (T) this;
        }
    }

    protected void OnDestroy()
    {
        if (instance == this)
        {
            instance = null;
        }
    }
}
Usage:

1
2
3
4
5
6
7
public class GameManager : Singleton<GameManager>
{
    protected GameManager() { }
 
    // Then add whatever code to the class you need as you normally would.
    ...
}

Conclusions

For Unity projects Singleton is one of the fundamental patterns (and not only for Unity). In our projects we will use classes named Managers. They will handle many different tasks, like scenes and transitions between them will be handled by SceneManager, or CameraManager will handle camera movement. So this is a small but fundamental post and it definitely will require to return to it. See you next time! =)



Privacy policyCookie policyTerms of service
Tulenber 2020