miaooo 发表于 2015-3-23 22:18

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”。

dongshan1986 发表于 2017-2-24 20:32

很不错

snaker7 发表于 2017-2-24 20:49

楼主是超人

aditya333 发表于 2017-2-24 20:33

顶顶多好

guduya 发表于 2017-2-24 20:47

真心顶

aditya333 发表于 2017-2-24 21:03

很好哦

风云浪子 发表于 2017-3-9 13:47

楼主是超人

风云浪子 发表于 2017-3-9 13:56

真心顶

tt_55 发表于 2017-3-9 14:04

难得一见的好帖

tt_55 发表于 2017-3-9 13:53

说的非常好
页: [1] 2 3 4 5 6 7 8 9
查看完整版本: unity 中的单件