Skip to content

Instantly share code, notes, and snippets.

@dpid
Created February 22, 2018 00:37
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 dpid/a19297ab242ec2fb78185878def84da4 to your computer and use it in GitHub Desktop.
Save dpid/a19297ab242ec2fb78185878def84da4 to your computer and use it in GitHub Desktop.
Unity C# Generic singleton class
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
private static T m_Instance = null;
public static T instance
{
get
{
// Instance requiered for the first time, we look for it
if( m_Instance == null )
{
m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
if (m_Instance != null)
{
m_Instance.Init();
}
}
return m_Instance;
}
}
public static bool Exists()
{
return (m_Instance != null);
}
// If no other monobehaviour request the instance in an awake function
// executing before this one, no need to search the object.
private void Awake()
{
if( m_Instance == null )
{
m_Instance = this as T;
m_Instance.Init();
}
}
// This function is called when the instance is used the first time
// Put all the initializations you need here, as you would do in Awake
public virtual void Init(){}
// Make sure the instance isn't referenced anymore when the user quit, just in case.
private void OnApplicationQuit()
{
m_Instance = null;
}
}
@dpid
Copy link
Author

dpid commented Feb 22, 2018

I'm not the original author of this. Not sure who is. However, I do find it to be a useful generic implementation. Most of the time I'm averse to using Singletons, but sometimes it's the simplest solution. My advise would be to use it with restraint.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment