- Published on
How to create a singleton game object in Unity
- Authors
- EvelynFull-time IndieDev.I'm Japanese, so please forgive me if my English is strange.
Welcome to the Evelyn GameDev Blog!
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.
Create a singleton game management object
Here is the script.
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
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
Wrap up
How was it? In this article, I introduced a technique called singleton.
I hope that Singleton's techniques will help you in your game development.
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.