Skip to content

Instantly share code, notes, and snippets.

@mstevenson
Created December 18, 2012 04:51
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save mstevenson/4325117 to your computer and use it in GitHub Desktop.
Save mstevenson/4325117 to your computer and use it in GitHub Desktop.
Generic Singleton classes for Unity. Use MonoBehaviourSingletonPersistent for any singleton that must survive a level load.
using UnityEngine;
using System.Collections;
public class MonoBehaviourSingleton<T> : MonoBehaviour
where T : Component
{
private static T _instance;
public static T Instance {
get {
if (_instance == null) {
var objs = FindObjectsOfType (typeof(T)) as T[];
if (objs.Length > 0)
_instance = objs[0];
if (objs.Length > 1) {
Debug.LogError ("There is more than one " + typeof(T).Name + " in the scene.");
}
if (_instance == null) {
GameObject obj = new GameObject ();
obj.hideFlags = HideFlags.HideAndDontSave;
_instance = obj.AddComponent<T> ();
}
}
return _instance;
}
}
}
public class MonoBehaviourSingletonPersistent<T> : MonoBehaviour
where T : Component
{
public static T Instance { get; private set; }
public virtual void Awake ()
{
if (Instance == null) {
Instance = this as T;
DontDestroyOnLoad (this);
} else {
Destroy (gameObject);
}
}
}
@djavadihamid
Copy link

"as T" was the problem I had.
thanks for your script that helped me.

@krummja
Copy link

krummja commented Apr 2, 2022

Great script! Saved my bacon during a Ludum Dare. :)

@Eloren1
Copy link

Eloren1 commented Feb 1, 2024

Sample usage

public class EverythingManager : MonoBehaviourSingleton<EverythingManager>
{

}

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