Skip to content

Instantly share code, notes, and snippets.

@kirillrybin
Last active November 26, 2015 20:03
Show Gist options
  • Save kirillrybin/9246150 to your computer and use it in GitHub Desktop.
Save kirillrybin/9246150 to your computer and use it in GitHub Desktop.
Singleton template for MonoBehaviour class in Unity3D
//#define LOG_MESSAGES
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
/**
Returns the instance of this singleton.
*/
public static T Instance
{
get
{
if (_instance == null)
{
_instance = (T)FindObjectOfType(typeof(T));
if (_instance == null)
{
#if LOG_MESSAGES
Debug.LogError("An instance of " + typeof(T) + "is needed in the scene, but there is none.");
#endif
}
}
return _instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment