Created
March 16, 2023 08:54
-
-
Save kirillrybin/2a6152f9e45408892651ff9e98d4fb42 to your computer and use it in GitHub Desktop.
[Unity] 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; | |
using System.Collections; | |
public class MonoBehaviourSingleton<T> : MonoBehaviour where T : MonoBehaviour | |
{ | |
private static T _instance = null; | |
private static bool _applicationIsQuitting = false; | |
[RuntimeInitializeOnLoadMethod] | |
private static void RunOnStart() | |
{ | |
Application.quitting += () => _applicationIsQuitting = true; | |
} | |
public static T Instance | |
{ | |
get | |
{ | |
if (_applicationIsQuitting) | |
return null; | |
if (ReferenceEquals(_instance, null)) | |
{ | |
_instance = (T)FindObjectOfType(typeof(T)); | |
if (ReferenceEquals(_instance, null)) | |
{ | |
_instance = (new GameObject(typeof(T).Name)).AddComponent<T>(); | |
} | |
DontDestroyOnLoad(_instance.gameObject); | |
} | |
return _instance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment