Last active
April 26, 2025 18:18
-
-
Save kurtdekker/775bb97614047072f7004d6fb9ccce30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
// by @kurtdekker - to make a simple Unity singleton that has no | |
// predefined data associated with it, eg, a high score manager. | |
// | |
// To use: access with SingletonSimple.Instance | |
// | |
// To set up: | |
// - Copy this file (duplicate it) | |
// - rename class SingletonSimple to your own classname | |
// - rename CS file too | |
// | |
// DO NOT PUT THIS IN ANY SCENE; this code auto-instantiates itself once. | |
// | |
// I do not recommend subclassing unless you really know what you're doing. | |
public class SingletonSimple : MonoBehaviour | |
{ | |
// This is really the only blurb of code you need to implement a Unity singleton | |
private static SingletonSimple _Instance; | |
public static SingletonSimple Instance | |
{ | |
get | |
{ | |
if (!_Instance) | |
{ | |
_Instance = new GameObject().AddComponent<SingletonSimple>(); | |
// name it for easy recognition | |
_Instance.name = _Instance.GetType().ToString(); | |
// mark root as DontDestroyOnLoad(); | |
DontDestroyOnLoad(_Instance.gameObject); | |
} | |
return _Instance; | |
} | |
} | |
// implement your Awake, Start, Update, or other methods here... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As I just recently realized, a
MonoBehaviour
will not be destroyed as long as there is a reference to it even if the underlying gameobject is destroyed. So, for this use case, wouldn't it make sense to instantly destroy the associated game object instead of making it survive scene changes withDontDestroyOnLoad
? After all you can always get your hands on theInstance
to destroy it if that would be needed.