Skip to content

Instantly share code, notes, and snippets.

@wilbefast
Last active August 29, 2015 14:02
Show Gist options
  • Save wilbefast/85de1a4500fcf51d7d5c to your computer and use it in GitHub Desktop.
Save wilbefast/85de1a4500fcf51d7d5c to your computer and use it in GitHub Desktop.
How to do Singleton scripts in Unity
public class Singleton : Monobehaviour
{
private static Singleton _instance = null;
public static Singleton instance
{
get
{
if (_instance == null)
{
// First try to find an instance already in the scene
_instance = GameObject.FindObjectOfType<Singleton>();
// Only instantiate if we're not cleaning up
// othewise objects will be leaked into the editor's version of the scene!
if(_instance == null && !_shuttingDown)
_instance = new GameObject("Singleton", typeof(Singleton)).GetComponent<Singleton>();
// Let the user know we're returing null
if(_instance == null)
Debug.LogError("What is dead may never die!");
}
return _instance;
}
}
private static bool _shuttingDown = false;
void OnApplicationQuit()
{
// This is important: we need to prevent instantiation during scene cleanup!
_shuttingDown = true;
}
void Awake()
{
if(_instance != null)
{
Debug.LogError("There can only be one!");
DestroyImmediate(this);
}
else
{
// if a job's worth doing it's worth doing twice... just to make sure
_instance = this;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment