Created
August 18, 2024 21:01
-
-
Save Abbabon/8b574524b1a233a8266aa81cad1f0c1c to your computer and use it in GitHub Desktop.
Generic Monobehaviour Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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