A Singleton is a design pattern used to ensure that only one instance of a class exists throughout the game. In Unity, this is often used for managing game managers, audio managers, input controllers, or any globally accessible system.
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager instance; // Static reference to the single instance
void Awake()
{
// Ensure only one instance exists
if (instance == null)
{
instance = this; // Set the instance to this object
DontDestroyOnLoad(gameObject); // Keep this object between scenes
}
else
{
Destroy(gameObject); // Destroy duplicate instances
}
}
}