component及剛體rigidbody用法


關於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()中調用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM