Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Last active March 22, 2024 10:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtdekker/775bb97614047072f7004d6fb9ccce30 to your computer and use it in GitHub Desktop.
Save kurtdekker/775bb97614047072f7004d6fb9ccce30 to your computer and use it in GitHub Desktop.
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...
}
@stickylab
Copy link

why you have to make this

_Instance = new GameObject().AddComponent();
// name it for easy recognition
_Instance.name = _Instance.GetType().ToString();

@hernans10
Copy link

Thank you for teaching the community, really appreciate it

@Leative
Copy link

Leative commented Mar 22, 2024

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 with DontDestroyOnLoad? After all you can always get your hands on the Instance to destroy it if that would be needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment