Last active
April 20, 2024 04:25
-
-
Save Trissiklikk/73f7f3063ac942ae9bd87f436e0dcf0a to your computer and use it in GitHub Desktop.
MonoBehaviourSingleton
This file contains 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; | |
namespace Game | |
{ | |
public class MonoBehaviourSingleton<T> : MonoBehaviour where T : Component | |
{ | |
/// <summary> | |
/// The instance of the singleton. | |
/// </summary> | |
protected static T _instance = null; | |
/// <summary> | |
/// This flag is used to check if the instance is destroyed or not. | |
/// </summary> | |
protected static bool _isDestroyed = false; | |
/// <summary> | |
/// Simple lock object to prevent multi-threading issues. | |
/// </summary> | |
protected static object _padlock = new object(); | |
/// <summary> | |
/// Get the instance of the singleton. | |
/// </summary> | |
public static T Instance | |
{ | |
get | |
{ | |
if (_isDestroyed) | |
{ | |
return null; | |
} | |
if (_instance == null) | |
{ | |
lock (_padlock) | |
{ | |
_instance = FindObjectOfType<T>(); | |
if (_instance == null) | |
{ | |
GameObject obj = new GameObject(); | |
obj.name = typeof(T).Name + " Auto-Generated"; | |
_instance = obj.AddComponent<T>(); | |
} | |
} | |
} | |
return _instance; | |
} | |
} | |
protected virtual void Awake() | |
{ | |
InitSingleton(); | |
} | |
protected virtual void OnDestroy() | |
{ | |
_isDestroyed = true; | |
} | |
/// <summary> | |
/// This method is logic that you need to initialize the singleton. | |
/// </summary> | |
protected virtual void InitSingleton() | |
{ | |
if (_instance != null && _instance != this) | |
{ | |
Destroy(this.gameObject); | |
return; | |
} | |
_isDestroyed = false; | |
_instance = this as T; | |
DontDestroyOnLoad(this.gameObject); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment