Skip to content

Instantly share code, notes, and snippets.

@Fenikkel
Last active June 12, 2024 10:13
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 adapted for Unity needs

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()
{
// Check if base and derived classes are the same type
if (this is not T)
{
Debug.LogError($"Base and derived classes are different types:\n\t- Base: {typeof(T)}\n\t- Derived: {GetType()}\nPlease modify {typeof(T)}\nDestroying the component in <b>{name}</b>.");
Destroy(this);
return false;
}
// Check if this instance is a duplicated
if (Instance != null && Instance != this)
{
if (this.gameObject.GetComponents<Component>().Length <= 2)
{
Debug.LogWarning($"Multiple instances of <b>{GetType().Name}</b>\nDestroying the gameobject <b>{name}</b>.");
Destroy(this.gameObject);
}
else
{
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.
}
return false;
}
// Set this instance as the selected
Instance = this as T;
return true;
}
}
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()
{
// Check if base and derived classes are the same type
if (this is not T)
{
Debug.LogError($"Base and derived classes are different types:\n\t- Base: {typeof(T)}\n\t- Derived: {GetType()}\nPlease modify {typeof(T)}\nDestroying the component in <b>{name}</b>.");
Destroy(this);
return false;
}
// Check if this instance is a duplicated
if (Instance != null && Instance != this)
{
Debug.LogWarning($"Multiple instances of <b>{GetType().Name}</b>\nDestroying the component in <b>{name}</b>.");
Destroy(this);
return false;
}
// Set this instance as the selected
Instance = this as T;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment