Skip to content

Instantly share code, notes, and snippets.

@Abbabon
Created August 18, 2024 21:01
Show Gist options
  • Save Abbabon/8b574524b1a233a8266aa81cad1f0c1c to your computer and use it in GitHub Desktop.
Save Abbabon/8b574524b1a233a8266aa81cad1f0c1c to your computer and use it in GitHub Desktop.
Generic Monobehaviour Singleton
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour where T: MonoBehaviour
{
private static T _instance;
// Property to access the instance
public static T Instance
{
get
{
if (_instance != null) return _instance;
// If the instance doesn't exist, find it in the scene
_instance = FindObjectOfType<T>();
if (_instance == null)
{
var singletonObject = new GameObject(typeof(T).Name);
_instance = singletonObject.AddComponent<T>();
}
DontDestroyOnLoad(_instance.gameObject);
return _instance;
}
}
protected void OnDestroy()
{
if (_instance == this)
{
_instance = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment