I'm IN! 15 in a row!
Joining for my 15th LD in a row!
Last time I shared a version of the Singleton Pattern as a script and I still think this is one of the Best Helper Classes I use in almost all of my Unity Projects, So I'll just copy it again!
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!