Created
November 15, 2016 07:07
-
-
Save codemaster/9b5da799955a9c6819467777e6b63f85 to your computer and use it in GitHub Desktop.
Unity Singleton Helper Classes
This file contains hidden or 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
/// <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() { } | |
} |
This file contains hidden or 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; | |
/// <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