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);
            }
        }
}
}

猜你喜欢

转载自blog.csdn.net/qq_34444468/article/details/79577640
今日推荐