Unity3D——GetComponentsInChildren()方法詳解

最近使用GetComponentsInChildren在做遊戲獲取孩子節點對象的時候遇到了問題,索性就花點時間理解透徹來,省的下次進坑;總結了三種情況,使用需謹慎。


一、能獲取到自己的情況

Transform[] trans = GetComponentsInChildren<Transform>();

因爲root對象以及其6個子對象都有Transform組件,所以獲取到的size是7,包含了root自身節點。


二、不能獲取到自身的情況


TestComponent[] trans = GetComponentsInChildren<TestComponent>();

此時是在root下面的子對象上掛在了TestComponent腳本(標識作用),這時沒有獲取到root自身節點


三、獲取到孩子的孩子對象的情況


TestComponent[] trans = GetComponentsInChildren<TestComponent>();
此時獲取到的結點包含了兒子節點、孫子節點和曾孫子節點,(看數組的順序,感覺有點像深度優先搜索的遍歷方式)。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章