Skip to content

Instantly share code, notes, and snippets.

@codemaster
Created November 15, 2016 07:07
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 codemaster/9b5da799955a9c6819467777e6b63f85 to your computer and use it in GitHub Desktop.
Save codemaster/9b5da799955a9c6819467777e6b63f85 to your computer and use it in GitHub Desktop.
Unity Singleton Helper Classes
/// <summary>
/// Singleton class
/// </summary>
public class Singleton<T> where T : new()
{
/// <summary>
/// Holds the actual instance
/// </summary>
private static T _instance;
/// <summary>
/// Accessor for the instance of the singleton
/// </summary>
public static T Instance {
get {
// Create a new instance if needed
if (null == _instance)
{
_instance = new T();
}
return _instance;
}
}
/// <summary>
/// Protected constructor to prohibit external creation
/// </summary>
protected Singleton() { }
}
using UnityEngine;
/// <summary>
/// Singleton behavior class
/// </summary>
public class SingletonBehaviour<T> : MonoBehaviour where T : Component
{
/// <summary>
/// Holds the actual instance
/// </summary>
private static T _instance;
/// <summary>
/// Accessor for the instance of the singleton
/// </summary>
public static T Instance {
get {
// Attempt to find an existing instance if necessary
if (null == _instance)
{
_instance = FindObjectOfType(typeof(T)) as T;
}
// If the instance is still null, create a new one
if (null == _instance)
{
var go = new GameObject();
// Hide the object so this script can manage it directly
go.hideFlags = HideFlags.HideAndDontSave;
_instance = go.AddComponent<T>();
}
return _instance;
}
}
/// <summary>
/// Constructor that deletes the object if an instance already exists
/// </summary>
public SingletonBehaviour()
{
if (null != _instance)
{
Destroy(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment