A basic singleton in Unity can be implemented like this:
using UnityEngine;
public class Managers : MonoBehaviour
{
private static Managers Instance;
public static Managers GetInstance() { return Instance; }
void Start()
{
GameObject go = GameObject.Find("@Managers");
Instance = go.GetComponent<Managers>();
}
void Update() { }
}
This works, but there's a problem:
- If another object tries to access the singleton before the manager object exists, it will be null.
So we need to make sure that:
If the manager GameObject exists:
- Just find it and assign it as the singleton.
If it doesn't exist:
- Create the manager GameObject and assign it as the singleton.
using UnityEngine;
public class Managers : MonoBehaviour
{
private static Managers s_Instance;
// 1.
// Use the Instance property to access s_Instance
public static Managers Instance
{
get
{
Init();
return s_Instance;
}
}
static void Init()
{
// 2.
// Called through the Instance property
if (s_Instance == null)
{
// 2-1.
// If s_Instance is null (which it will be the first time),
// try to find a GameObject named "@Managers"
GameObject go = GameObject.Find("@Managers");
// 3.
// If no such GameObject exists (i.e., not found in the Hierarchy)
if (go == null)
{
// 4.
// Create a new GameObject named "@Managers"
// and add the Managers component to it
go = new GameObject() { name = "@Managers" };
go.AddComponent<Managers>();
}
// 3-1.
// If the GameObject "@Managers" already exists,
// make sure it is not destroyed on scene changes
// and assign the Managers component to s_Instance
DontDestroyOnLoad(go);
s_Instance = go.GetComponent<Managers>();
}
}
}
This way, s_Instance will always refer to the correct Managers instance.
Top comments (2)
Strictly speaking, this isn't a Singleton. It's a utility to access an instance.
A Singleton should ensure that only insurance of the class exists. Singleton classes typically have private constructors. There is nothing here preventing another piece of code from creating a GameObject named "@Manager" or adding a Manager component to another GameObject.
This approach is fine for managing access as long as it's not overused. But I think it's important to understand the differences.
Hi, thanks for comment!
Yeah this post is basically saying "How to use Singleton pattern in Unity".
This is just basic case, and in real product, don't use like this. There should be more encapsulation, and just make they can approach to single instance.
It's for Ensuring unity, and if it doesn't exist, instantiate one object, and make it ensure unity. I just wanna explain simple case! ;>