Unity3D学习笔记——递归+非递归遍历GameObject的子物体


  在Unity3D中没有提供直接的方法获取某个GameObject的子GameObject,但是所有的GameObject都有transform对象,所以,一般是通过获取子GameObject的transform来达到遍历子GameObject的目的。官网手册中“Transform”页面给出了如下示例代码:

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class example : MonoBehaviour {
 5     void Example() {
 6         foreach (Transform child in transform) {
 7             child.position += Vector3.up * 10.0F;
 8         }
 9     }
10 }

  但是,这段代码只能遍历该GameObject的直接子GameObject,而要遍历该GameObject的所有子GameObject,则需要进行递归:

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class example: MonoBehaviour {
 5     void Example() {
 6         Recursive(gameObject);
 7     }
 8     
 9     private void Recursive(GameObject parentGameObject){
10         //Do something you want
11         //......
12         foreach (Transform child in parentGameObject.transform){
13             Recursive(child.gameObject);
14         }
15     }                                                        
16 }    

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM