Skip to content

Instantly share code, notes, and snippets.

@BrianOstrander
Created March 11, 2015 16:41
Show Gist options
  • Save BrianOstrander/449b2e8275d438025b8d to your computer and use it in GitHub Desktop.
Save BrianOstrander/449b2e8275d438025b8d to your computer and use it in GitHub Desktop.
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