Created
September 17, 2013 22:09
-
-
Save capyvara/6601391 to your computer and use it in GitHub Desktop.
MonoBehaviour based singletons
This file contains 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; | |
namespace Framework | |
{ | |
/// <summary> | |
/// Simple singleton, automatically find a instance and caches it | |
/// Implementors should make all public methods and properties as static and access Instance | |
/// </summary> | |
public abstract class Singleton<T> : MonoBehaviour where T: MonoBehaviour | |
{ | |
static T _instance; | |
protected static T Instance | |
{ | |
get | |
{ | |
if (_instance) | |
return _instance; | |
_instance = FindObjectOfType(typeof(T)) as T; | |
if (_instance) | |
return _instance; | |
return null; | |
} | |
set | |
{ | |
_instance = value; | |
} | |
} | |
protected virtual void OnDestroy() | |
{ | |
if (_instance == this) | |
_instance = null; | |
} | |
public static bool IsValid | |
{ | |
get { return _instance != null; } | |
} | |
} | |
/// <summary> | |
/// Singleton that allows auto loading of the instance from resources, use when serialization is required | |
/// </summary> | |
public abstract class AutoLoadSingleton<T> : Singleton<T> where T: MonoBehaviour | |
{ | |
static bool _quitting; | |
protected new static T Instance | |
{ | |
get | |
{ | |
var instance = Singleton<T>.Instance; | |
if (instance) | |
return instance; | |
if (_quitting) | |
return null; | |
var prefab = Resources.Load(typeof(T).FullName) as GameObject; | |
if (prefab != null) | |
{ | |
var component = prefab.GetComponent<T>(); | |
if (component != null) | |
{ | |
instance = Instantiate(component) as T; | |
if (instance) | |
{ | |
instance.name = typeof(T).FullName; | |
Singleton<T>.Instance = instance; | |
return instance; | |
} | |
} | |
} | |
return null; | |
} | |
} | |
protected virtual void OnApplicationQuit() | |
{ | |
_quitting = true; | |
} | |
} | |
/// <summary> | |
/// Singleton that allows auto creation (not loading) of the instance, use when no serialization is needed | |
/// </summary> | |
public abstract class AutoCreateSingleton<T> : Singleton<T> where T: MonoBehaviour | |
{ | |
static bool _quitting; | |
protected new static T Instance | |
{ | |
get | |
{ | |
var instance = Singleton<T>.Instance; | |
if (instance) | |
return instance; | |
if (_quitting) | |
return null; | |
var go = new GameObject(typeof(T).FullName); | |
instance = go.AddComponent<T>(); | |
Singleton<T>.Instance = instance; | |
return instance; | |
} | |
} | |
protected virtual void OnApplicationQuit() | |
{ | |
_quitting = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment