在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 }
