MyComponment myCom=gameObject.GetComponent<MyComponment>();
//GetCompoment <T>()從當(dāng)前游戲?qū)ο螳@取組件T,只在當(dāng)前游戲?qū)ο笾蝎@取妄迁,沒得到的就返回null尿招,不會(huì)去子物體中去尋找溜腐。
MyComponment childCom=gameObject.GetComponentInChildren<MyComponment>();
//GetCompomentInChildren<T>()先從本對(duì)象中找钱豁,有就返回,沒就子物體中找吉执,知道找完為止疯淫。
MyComponment[] comS=gameObject.GetComponents<MyComponment>();
//GetComponents<T>()獲取本游戲?qū)ο蟮乃蠺組件,不會(huì)去子物體中找戳玫。
MyComponment[] comS1=gameObject.GetComponentsInChildren<MyComponment>();
MyComponment[] comSTrue=gameObject.GetComponentsInChildren<MyComponment>(true);
//GetComponentsInChildren<T>()=GetComponentsInChildren<T>(true)取本游戲?qū)ο蠹白游矬w的所有組件
MyComponment[] comSFalse=gameObject.GetComponentsInChildren<MyComponment>(false);
//GetComponentsInChildren<T>(false)取本游戲?qū)ο蠹白游矬w的所有組件 除開非活躍的游戲?qū)ο笪醪簦皇窃摻M件是否活躍。
例如:獲取另一個(gè)腳本中的變量
moveCube = GetComponent<MoveCube> ();
Debug.Log ("GetComponent<MoveCube> () debug "+moveCube.speed);
經(jīng)過測(cè)試用GetComponent()獲取Transform組件咕宿,比預(yù)先保存其引用后再調(diào)用要慢得多币绩,建議少用蜡秽。