Created
March 11, 2015 16:41
-
-
Save BrianOstrander/449b2e8275d438025b8d to your computer and use it in GitHub Desktop.
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; | |
using System.Collections; | |
namespace LunraGames.AdvancedObjects { | |
/// <summary> | |
/// A class to manage scripts and prefabs that should only be spawned once. | |
/// </summary> | |
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour { | |
public const string InstancePropertyName = "Instance"; | |
private static T instance; | |
/// <summary> | |
/// Gets the spawned instance of this singleton. | |
/// </summary> | |
/// <value>Spawned instance of this class, or null if it hasn't been spawned or has been destroyed.</value> | |
public static T Instance { | |
get { | |
if (instance == null || instance.gameObject == null) { | |
GameObject existingInstance = GameObject.Find(typeof(T).Name); | |
if (existingInstance != null) { | |
instance = (T)System.Convert.ChangeType(existingInstance.GetComponent(typeof(T)), typeof(T)); | |
} | |
} | |
return instance; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment