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

时间:2023-12-09 14:49:01

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

 using UnityEngine;
using System.Collections; public class example : MonoBehaviour {
void Example() {
foreach (Transform child in transform) {
child.position += Vector3.up * 10.0F;
}
}
}

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

 using UnityEngine;
using System.Collections; public class example: MonoBehaviour {
void Example() {
Recursive(gameObject);
} private void Recursive(GameObject parentGameObject){
//Do something you want
//......
foreach (Transform child in parentGameObject.transform){
Recursive(child.gameObject);
}
}
}