using UnityEngine;
public abstract class SingletonMono<T> : MonoBehaviour where T : Component
{
private static T m_instance;
private static bool m_isAppQuitting = false;
public static T GetInstance()
{
if (m_isAppQuitting)
{
return null;
}
if (m_instance == null)
{
m_instance = FindObjectOfType<T>();
if (m_instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
m_instance = obj.AddComponent<T>();
}
}
return m_instance;
}
protected virtual void Awake()
{
if (m_instance == null)
{
m_instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (m_instance != this as T)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
private void OnApplicationQuit()
{
m_isAppQuitting = true;
}
}
IMPROPER USAGE
- Don’t call GetInstance from another objects Awake function
- Don’t use 1 singleton to access every important variable in your game
- Don’t use singletons just to access data or references if they are not part of the design
MAIN AREAS THEY WON’T WORK
- Unit Tests because they require copies/mock objects to test
- Multithreading