Skip to content

Instantly share code, notes, and snippets.

@kirillrybin
Created March 16, 2023 08:54
Show Gist options
  • Save kirillrybin/2a6152f9e45408892651ff9e98d4fb42 to your computer and use it in GitHub Desktop.
Save kirillrybin/2a6152f9e45408892651ff9e98d4fb42 to your computer and use it in GitHub Desktop.
[Unity] MonoBehaviourSingleton
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