using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour where T : Component
{
private static T instance;
private static bool m_applicationIsQuitting = false;
public static T GetInstance()
{
if (m_applicationIsQuitting) { return null; }
if (instance == null)
{
instance = FindObjectOfType<T>();
if (instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
instance = obj.AddComponent<T>();
}
}
return instance;
}
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (instance != this as T)
{
Destroy(gameObject);
}
else { DontDestroyOnLoad(gameObject); }
}
private void OnApplicationQuit()
{
m_applicationIsQuitting = 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
|