转 Unity 2017 GetComponent 详解

https://www.jianshu.com/p/58fd276d3e09

MyComponment myCom=gameObject.GetComponent<MyComponment>();  
//GetCompoment <T>()从当前游戏对象获取组件T,只在当前游戏对象中获取,没得到的就返回null,不会去子物体中去寻找。
  
MyComponment childCom=gameObject.GetComponentInChildren<MyComponment>();  
//GetCompomentInChildren<T>()先从本对象中找,有就返回,没就子物体中找,知道找完为止。
  
MyComponment[] comS=gameObject.GetComponents<MyComponment>();  
//GetComponents<T>()获取本游戏对象的所有T组件,不会去子物体中找。

MyComponment[] comS1=gameObject.GetComponentsInChildren<MyComponment>();    
MyComponment[] comSTrue=gameObject.GetComponentsInChildren<MyComponment>(true); 
//GetComponentsInChildren<T>()=GetComponentsInChildren<T>(true)取本游戏对象及子物体的所有组件 
  
MyComponment[] comSFalse=gameObject.GetComponentsInChildren<MyComponment>(false); 
//GetComponentsInChildren<T>(false)取本游戏对象及子物体的所有组件 除开非活跃的游戏对象,不是该组件是否活跃。

例如:获取另一个脚本中的变量

moveCube = GetComponent<MoveCube> ();  
Debug.Log ("GetComponent<MoveCube> () debug "+moveCube.speed); 

经过测试用GetComponent()获取Transform组件,比预先保存其引用后再调用要慢得多,建议少用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值