unity 中的单件
从下面这个类派生的所有类,将自动获得单件功能: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。
[*]对于那些非唯一的prefab实例使用单件管理器(例如Player)。不要为了坚持这条原则把类的层次关系复杂化,宁愿在你的GameManager(或其他合适的管理器中)中持有一个它们的引用。
[*]对于外部经常使用的共有变量和方法定义为static,这样你可以这样简便的书写“GameManager.Player”,而不用写成“GameManager.Instance.player”。
很不错 楼主是超人 顶顶多好 真心顶 很好哦 楼主是超人 真心顶 难得一见的好帖 说的非常好