Published on

How to create a singleton game object in Unity

Authors
  • Evelyn

Please share this article if you like!

Welcome to the Evelyn GameDev Blog!

A bug was created because I mistakenly placed two or more game objects that manage the initialization and progress of the game.

You may not make many of the above mistakes, but it would be nice to have a mechanism to assure that no single game object exists.

In this article, I will introduce a mechanism called singleton, which is very effective in such cases.

Table of Contents

Create a singleton game management object

Here is the script.

First of all, it's useful to create the following script called SingletonMonoBehaviour!

SingletonMonoBehaviour.cs

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

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

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (T)FindObjectOfType(typeof(T));

                if (instance == null)
                {
                    Debug.LogError(typeof(T) + "does not exist in this scene");
                }
            }

            return instance;
        }
    }

    private void Awake()
    {
        if (this != Instance)
        {
            Destroy(gameObject);
            return;
        }
    }
}

Usage

You can use the previous script by writing something like the following

Then create a script that inherits SingletonMonoBehaviour.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameController : SingletonMonoBehaviour<GameController>
{
    private void Start()
    {
        // this is a singleton game object

        // If you want to utilize the same game object across scenes, run the following code
        // DontDestroyOnLoad(gameObject);
    }
}

It's very simple, but that's all it takes to create a singleton game object.

Examples of use

And I think the following is a case of a singleton game objectout that can be used across scenes.

  • Manage BGM and SE for games
  • Display effects at the tap position in smartphone games
  • Manage to show or hide in-app advertisements
This method is especially effective when you want to perform common operations in multiple scenes.

Wrap up

How was it? In this article, I introduced a technique called singleton.

However, if you use too much, it will be difficult to test, so you may want to use it in a limited way.

I hope that Singleton's techniques will help you in your game development.

Summary of this article

Let's use a singleton to guarantee it's the only game object!

Thank you for reading to the end.

I'm glad to see you again in another article.

Please share this article if you like!