關於getcomponent函數,rigidbody(2d)的嵌套關系及用法
1.getcomponent函數
在unity中腳本可以看成是可定義的組件,我們經常要訪問同一對象或不同對象中的腳本,可以運用getcomponent<>來訪問其他腳本,
本例的另外兩個腳本中都有公有變量,假設一個腳本名為anotherscript,另一個為Yetanotherscript。我們需要在usinganotherscript
中訪問這兩個腳本。
1 public GameObject otherGameObject; 2 private Anotherscript anotherscript; 3 private YetAnotherScript yetanotherscript; 4 void Awake{ 5 anotherscript=getcomponent<Anotherscript>; 6 yetanotherscript=otherGameObject.getcomponent<Yetanotherscript>; 7 }
在rigidbody中,同樣可以使用此函數來綁定剛體對象
1 public Rigidbody boat ; 2 void Start(){ 3 boat=this.GetComponent<Rigidbody>(); 4 }
此例先聲明一個名為boat的變量,需要使用getcomponent方法來取得剛體組件的屬性;
注: getcomponent方法對內存消耗較大,盡量少用,並且需要在Start(),或者Awake()中調用。