Created
February 7, 2020 04:13
-
-
Save Streamweaver/12dd94635ec5d3f8a30822b3717cf4aa to your computer and use it in GitHub Desktop.
Singleton Class for Unity I like
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; | |
// Got this online and want to reuse for simple singletons. | |
namespace Streamweaver.Util | |
{ | |
// Class taken from The Secret Labs Unity Cookbook repo | |
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour | |
{ | |
public static T instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
_instance = FindOrCreateInstance(); | |
} | |
return _instance; | |
} | |
} | |
private static T _instance; | |
private static T FindOrCreateInstance() | |
{ | |
var instance = GameObject.FindObjectOfType<T>(); | |
if (instance != null) | |
{ | |
return instance; | |
} | |
var name = typeof(T).Name + " Singleton"; | |
var containerGameObject = new GameObject(name); | |
var singletonComponent = containerGameObject.AddComponent<T>(); | |
return singletonComponent; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment