A singleton is a class that allows only one instance of itself to exist. Any script can access it from anywhere without needing a reference.
- Only one instance exists in the game
- Accessible from any script using ClassName.Instance
- Persists across scenes (optional)
Basic Singleton Implementation
This is the simplest singleton pattern.
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
void Awake()
{
Instance = this;
}
public void StartGame()
{
Debug.Log("Game Started");
}
}
Now any script can call GameManager.Instance.StartGame() without finding or dragging references.
Complete Singleton (No Duplicates)
This version prevents duplicate instances from being created.
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance;
void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject); // Destroy duplicate
}
}
public void PlaySound(AudioClip clip)
{
AudioSource.PlayClipAtPoint(clip, Vector3.zero);
}
}
If a second AudioManager tries to spawn, it destroys itself. The first one remains.
Using Singleton from Any Script
Once you have a singleton, any script can access it directly. This is the main benefit - no dragging references in Inspector.
public class Player : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Coin"))
{
GameManager.Instance.AddScore(10);
AudioManager.Instance.PlayCoinSound();
}
}
}
No need to drag references. Just call ClassName.Instance.MethodName() from anywhere.
Singleton vs Static Class
| Singleton | Static Class |
|---|---|
| Inherits from MonoBehaviour | Cannot inherit from MonoBehaviour |
| Can use Unity methods (Start, Update) | No Unity lifecycle methods |
| Can be placed in the scene | Cannot be placed in the scene |
| Supports DontDestroyOnLoad | No scene persistence |
When to Use Singleton
- Good for: GameManager, AudioManager, ScoreManager, UIManager, SaveSystem.
- Not Good For: Player (if multiple players), Enemies, Bullets, Items.