Created
March 19, 2017 00:08
-
-
Save mrcarriere/c0d377cb593c6bbcdae4038a6b64f20f to your computer and use it in GitHub Desktop.
Generic Singleton without persistence across scenes.
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 SceneSingleton<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>(); | |
} | |
return _instance; | |
} | |
} | |
protected virtual void Awake() | |
{ | |
if (_instance == null) | |
{ | |
_instance = this as T; | |
} | |
else | |
{ | |
Destroy(gameObject); | |
} | |
} | |
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