从下面这个类派生的所有类,将自动获得单件功能:
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour{
protected static T instance;
/** Returns the instance of this singleton. */
public static T Instance {
get {
if(instance == null) {
instance = (T) FindObjectOfType(typeof(T));
if (instance == null) {
Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none.");
}
} return instance;
}
}
}单件可以作为一些管理器,例如ParticleManager或者AudioManager亦或者GUIManager。