Created
May 8, 2019 12:10
-
-
Save 0x61726b/686b7f585353442b33bb7984a0ca0e74 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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