Skip to content

Instantly share code, notes, and snippets.

@bartofzo
Last active October 1, 2019 11:15
Show Gist options
  • Save bartofzo/17bd5ffcae9f5ceac8f9af66318a3442 to your computer and use it in GitHub Desktop.
Save bartofzo/17bd5ffcae9f5ceac8f9af66318a3442 to your computer and use it in GitHub Desktop.
Boilerplate for making a Unity GameObject a singleton
/**
*
* Boilerplate for making a Unity GameObject a singleton
* 2019 - Bart van de Sande / Nonline
*
*/
using UnityEngine;
public class MonoBehaviourSingleton<T> : MonoBehaviour where T : MonoBehaviourSingleton<T>
{
private static T _instance;
/// <summary>
/// Returns if there is an instance of this
/// </summary>
public static bool HasInstance => _instance != null;
/// <summary>
/// Access the singleton instance, will create one if it doesn't exist yet
/// </summary>
public static T Instance
{
get
{
if (_instance == null)
new GameObject(typeof(T).Name).AddComponent<T>();
return _instance;
}
}
protected virtual void Awake()
{
if (_instance != null)
{
Destroy(this.gameObject);
return;
}
_instance = this as T;
DontDestroyOnLoad(this.gameObject);
}
protected virtual void OnDestroy()
{
if (_instance == this)
_instance = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment