Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@huihut
Created December 15, 2020 09:57
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 huihut/305aaa2a8e0988d18ff656e65e9d6a93 to your computer and use it in GitHub Desktop.
Save huihut/305aaa2a8e0988d18ff656e65e9d6a93 to your computer and use it in GitHub Desktop.
Unity singleton pattern base class
public class SingletonBase<T> where T : new()
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
instance = new T();
return instance;
}
}
using UnityEngine;
public class SingletonMonoBase<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
{
GameObject obj = new GameObject();
DontDestroyOnLoad(obj);
obj.name = typeof(T).ToString();
instance = obj.AddComponent<T>();
}
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment