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