Unity中遍歷一個物體的子物體的三種方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwitchButtonIsShow : MonoBehaviour {
    private GameObject but;                 //需要遍歷子物體的母體
    public List<Transform> butArray;       //遍歷的結果數組
// Use this for initialization
void Start () {
        but = GameObject.FindGameObjectWithTag("Button");   //查找物體
        if (but != null)
        {
            Debug.Log(but.name);

            //遍歷所有的子物體以及孫物體,並且遍歷包含本身
            //for (int i = 0; i < but.GetComponentsInChildren<Transform>(true).Length; i++)
            //{
            //    butArray.Add(but.GetComponentsInChildren<Transform>()[i]);
            //}

            //作用同上
            //foreach(Transform child in but.GetComponentsInChildren<Transform>(true))
            //{
            //    butArray.Add(child);
            //}

            ////只遍歷所有的子物體,沒有孫物體  ,遍歷不包含本身
            foreach (Transform child in but.transform)
            {
                butArray.Add(child);
            }
        }
}
}
發佈了35 篇原創文章 · 獲贊 20 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章