Skip to content

Instantly share code, notes, and snippets.

@TarasOsiris
Last active November 20, 2018 15:03
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 TarasOsiris/e41a151366a37143a76e to your computer and use it in GitHub Desktop.
Save TarasOsiris/e41a151366a37143a76e to your computer and use it in GitHub Desktop.
Singleton MonoBehavior for Unity3d
using JetBrains.Annotations;
using UnityEngine;
[PublicAPI]
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType(typeof(T)) as T;
if (_instance == null)
{
Debug.Log("No instance of " + typeof(T) + ", a temporary one is created.");
_instance = new GameObject("Temp Instance of " + typeof(T), typeof(T)).GetComponent<T>();
}
_instance.Init();
}
return _instance;
}
}
// If no other monobehaviour request the instance in an awake function
// executing before this one, no need to search the object.
void Awake()
{
if (_instance == null)
{
DontDestroyOnLoad(gameObject);
_instance = this as T;
_instance.Init();
}
else
{
Destroy(gameObject);
}
}
// This function is called when the instance is used the first time
// Put all the initializations you need here, as you would do in Awake
public virtual void Init()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment