Last active
November 20, 2018 15:03
-
-
Save TarasOsiris/e41a151366a37143a76e to your computer and use it in GitHub Desktop.
Singleton MonoBehavior for Unity3d
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 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