Skip to content

Instantly share code, notes, and snippets.

@Fenikkel
Last active April 14, 2025 11:16
Show Gist options
  • Save Fenikkel/ad033a959191ef2817ac328f721373ab to your computer and use it in GitHub Desktop.
Save Fenikkel/ad033a959191ef2817ac328f721373ab to your computer and use it in GitHub Desktop.
Unity singleton

Singleton for Unity

Singleton example

 

Notes

Simple tu use and foolproof. It uses abstraction to make it almost invisible on your code and easy to reuse it.

 

Usage

  1. Inherid on your class:
    public class MyMonoBehaviour : Singleton<MyMonoBehaviour>
    {
        public bool ExampleBool;
    }
  1. Call it from another script:
    MyMonoBehaviour.Instance.ExampleBool;

Same instructions for SingletonPersistent.cs

 

Compatibility

  • Any Unity version
  • Any pipeline (Build-in, URP, HDRP, etc)

 

Support

⭐ Star if you like it
❤️️ Follow me for more

using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance { get; private set; }
protected virtual void Awake()
{
CheckSingleton();
}
public virtual bool CheckSingleton()
{
// Checks if the programmer has mistyped the inheritance
if (this is not T)
{
Debug.LogError($"Inheritance mistype in <b>{this.GetType()}</b> script. Change {typeof(T)} for {this.GetType()}\nDestroying the component in <b>{name}</b>.");
DestroyImmediate(this);
return false;
}
// Check if this instance is a duplicated
if (Instance != null && Instance != this)
{
// Check if base and derived classes are the same type
if (this.GetType() != Instance.GetType())
{
Debug.LogWarning($"The types <b>{this.GetType()}</b> and <b>{Instance.GetType()}</b> derives from the same class.\n<b>{this.GetType()}</b> will be removed.");
}
// Check if the duplicate is in the same GameObject
if (1 < this.gameObject.GetComponents<T>().Length)
{
Debug.LogWarning($"Multiple instances of <b>{GetType().Name}</b>\nDestroying the component in <b>{name}</b>.");
DestroyImmediate(this); // Instant destruction to avoid waiting for the end of the frame.
}
else
{
Debug.LogWarning($"Multiple instances of <b>{GetType().Name}</b>\nDestroying the gameobject <b>{name}</b>.");
DestroyImmediate(this.gameObject);
}
return false;
}
// Set this instance as the selected
Instance = this as T;
return true;
}
}
using UnityEngine;
public abstract class SingletonPersistent<T> : Singleton<T> where T : MonoBehaviour
{
protected override void Awake()
{
CheckSingleton();
}
public override bool CheckSingleton()
{
bool isOriginal = base.CheckSingleton();
if (isOriginal)
{
int numAttachedComponents = gameObject.GetComponents<Component>().Length;
if (2 < numAttachedComponents)
{
Debug.LogWarning($"The persistent singleton <b>{name}</b> have <b>{numAttachedComponents - 2}</b> extra components appart of the Transform and himself. This extra components may be rubish in other scenes.");
}
this.transform.parent = null; // Unparent for the sake of the DontDestroyOnLoad
DontDestroyOnLoad(gameObject);
}
return isOriginal;
}
}
@Fenikkel
Copy link
Author

If you are inheriting a class that is already inheriting the Singleton like:
public class MyDerivedClass : MyMonoBehaviour

You can call the functions of the derived class parsing the type:
((MyDerivedClass)MyDerivedClass.Instance).MyDerivedFunction();

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