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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章