Skip to content

Instantly share code, notes, and snippets.

@dotKokott
Created February 9, 2017 22:33
Show Gist options
  • Save dotKokott/f7e2a10021a228b8f55c2dbf639d7d4f to your computer and use it in GitHub Desktop.
Save dotKokott/f7e2a10021a228b8f55c2dbf639d7d4f to your computer and use it in GitHub Desktop.
Makes any Unity monobehaviour a singleton that inherits from it
//FROM http://www.glenstevens.ca/unity3d-best-practices/
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
protected 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)
{
Debug.LogError("An instance of " + typeof(T) +
" is needed in the scene, but there is none.");
}
}
return instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment