Skip to content

Instantly share code, notes, and snippets.

@0x61726b
Created May 8, 2019 12:10
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 0x61726b/686b7f585353442b33bb7984a0ca0e74 to your computer and use it in GitHub Desktop.
Save 0x61726b/686b7f585353442b33bb7984a0ca0e74 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _sInstance;
public static T Instance
{
get
{
if ((Object)(object)MonoSingleton<T>._sInstance != (Object)null)
{
return MonoSingleton<T>._sInstance;
}
MonoSingleton<T>._sInstance = (T)Object.FindObjectOfType(typeof(T));
if (Object.FindObjectsOfType(typeof(T)).Length > 1)
{
Debug.LogError("[Singleton] Something went really wrong - there should never be more than 1 singleton! Reopening the scene might fix it.");
return MonoSingleton<T>._sInstance;
}
if ((Object)(object)MonoSingleton<T>._sInstance == (Object)null)
{
//GameObject gameObject = new GameObject();
//MonoSingleton<T>._sInstance = gameObject.AddComponent<T>();
//gameObject.name = "(singleton) " + typeof(T).ToString();
//Object.DontDestroyOnLoad(gameObject);
Debug.Log("[Singleton] An instance of " + typeof(T) + " is needed in the scene, so was NOT created with DontDestroyOnLoad.");
}
return MonoSingleton<T>._sInstance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment