时间:2021-07-01 10:21:17 帮助过:32人阅读
1.getcomponent函数
在unity中脚本可以看成是可定义的组件,我们经常要访问同一对象或不同对象中的脚本,可以运用getcomponent<>来访问其他脚本,
本例的另外两个脚本中都有公有变量,假设一个脚本名为anotherscript,另一个为Yetanotherscript。我们需要在usinganotherscript
中访问这两个脚本。
- <span style="color: #008080">1</span> <span style="color: #0000ff">public</span><span style="color: #000000"> GameObject otherGameObject;
- </span><span style="color: #008080">2</span> <span style="color: #0000ff">private</span><span style="color: #000000"> Anotherscript anotherscript;
- </span><span style="color: #008080">3</span> <span style="color: #0000ff">private</span><span style="color: #000000"> YetAnotherScript yetanotherscript;
- </span><span style="color: #008080">4</span> <span style="color: #0000ff">void</span><span style="color: #000000"> Awake{
- </span><span style="color: #008080">5</span> anotherscript=getcomponent<Anotherscript><span style="color: #000000">;
- </span><span style="color: #008080">6</span> yetanotherscript=otherGameObject.getcomponent<Yetanotherscript><span style="color: #000000">;
- </span><span style="color: #008080">7</span> }
在rigidbody中,同样可以使用此函数来绑定刚体对象
- <span style="color: #008080">1</span> <span style="color: #0000ff">public</span><span style="color: #000000"> Rigidbody boat ;
- </span><span style="color: #008080">2</span> <span style="color: #0000ff">void</span><span style="color: #000000"> Start(){
- </span><span style="color: #008080">3</span> boat=this.GetComponent<Rigidbody>()<span style="color: #000000">;
- </span><span style="color: #008080">4</span> }
此例先声明一个名为boat的变量,需要使用getcomponent方法来取得刚体组件的属性;
注: getcomponent方法对内存消耗较大,尽量少用,并且需要在Start(),或者Awake()中调用。
component及刚体rigidbody用法
标签:mil 刚体 脚本 art 一个 start unit 并且 变量