Last active
October 1, 2019 11:15
-
-
Save bartofzo/17bd5ffcae9f5ceac8f9af66318a3442 to your computer and use it in GitHub Desktop.
Boilerplate for making a Unity GameObject a singleton
This file contains hidden or 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
/** | |
* | |
* 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