Singleton Trick
Joining for my 14th LD in a row!
As a little bonus, I wanted to share a helpful Unity tip that I've been using in my last few projects — especially handy during a game jam when speed matters.
It’s about the Singleton pattern, which is super useful for scripts where you only ever want one instance in your game (like your SceneManager, AudioManager, etc.).
I used to write the singleton logic manually in each of these scripts. But now, I use this handy base class instead — whenever I want singleton behavior, I just make my script derive from Singleton<T>!
For example:
public class SceneManager : Singleton<SceneManager>
instead of
public class SceneManager : MonoBehaviour
I hope this is helpful to someone out there, here is the script: ``` using UnityEngine;
public class Singleton : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
// Search for existing instance.
_instance = FindFirstObjectByType<T>();
// Create new instance if one doesn't already exist.
if (_instance == null)
{
// Ensure that there's a GameObject to attach the singleton to.
var singletonObject = new GameObject();
_instance = singletonObject.AddComponent<T>();
singletonObject.name = typeof(T).ToString() + " (Singleton)";
// Make sure the singleton persists across scenes.
DontDestroyOnLoad(singletonObject);
}
}
return _instance;
}
}
protected virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(gameObject);
}
}
} ``` Good luck to everyone jamming!