当前位置: 代码迷 >> 综合 >> Unity中遍历一个物体的子物体的三种方法
  详细解决方案

Unity中遍历一个物体的子物体的三种方法

热度:76   发布时间:2023-09-23 02:00:21.0
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);
            }
        }
}
}