Skip to content

Instantly share code, notes, and snippets.

@mrcarriere
Created March 19, 2017 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcarriere/c0d377cb593c6bbcdae4038a6b64f20f to your computer and use it in GitHub Desktop.
Save mrcarriere/c0d377cb593c6bbcdae4038a6b64f20f to your computer and use it in GitHub Desktop.
Generic Singleton without persistence across scenes.
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