Skip to content

Instantly share code, notes, and snippets.

@Streamweaver
Created February 7, 2020 04:13
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 Streamweaver/12dd94635ec5d3f8a30822b3717cf4aa to your computer and use it in GitHub Desktop.
Save Streamweaver/12dd94635ec5d3f8a30822b3717cf4aa to your computer and use it in GitHub Desktop.
Singleton Class for Unity I like
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