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 }    

 

posted on 2014-04-14 20:59  水煮鱼丸  阅读(10072)  评论(0编辑  收藏  举报

导航