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

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

 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,则须要进行递归:code

 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 }    
相关文章
相关标签/搜索