Created
March 19, 2017 00:07
-
-
Save mrcarriere/5b6fa9362270c2658c2e2dbc2aad420b to your computer and use it in GitHub Desktop.
Generic Singleton for Unity
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; | |
public class Singleton<T> : MonoBehaviour | |
where T : Component | |
{ | |
private static bool _applicationIsQuitting = false; | |
private static T _instance = null; | |
public static T instance | |
{ | |
get | |
{ | |
if (_instance == null && !_applicationIsQuitting) | |
{ | |
_instance = FindObjectOfType<T>(); | |
if (_instance == null) | |
_instance = new GameObject("_" + typeof(T).Name).AddComponent<T>(); | |
DontDestroyOnLoad(_instance); | |
} | |
return _instance; | |
} | |
} | |
protected virtual void Awake() | |
{ | |
if (_instance == null) | |
{ | |
_instance = this as T; | |
DontDestroyOnLoad(gameObject); | |
} | |
else | |
{ | |
Destroy(gameObject); | |
} | |
} | |
public void ForceLoad() | |
{ | |
// no-op, force the lazy load of the singleton. | |
} | |
protected virtual void OnApplicationQuit() | |
{ | |
_instance = null; | |
Destroy(gameObject); | |
_applicationIsQuitting = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment