Created
February 22, 2018 00:37
-
-
Save dpid/a19297ab242ec2fb78185878def84da4 to your computer and use it in GitHub Desktop.
Unity C# Generic singleton class
This file contains 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; | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.