Por meio da combinação de Find e GetChild em Transform, o algoritmo recursivo é usado para realizar a classe auxiliar para encontrar objetos filho quando a hierarquia é desconhecida. (Algoritmo de gravação para visualização posterior)
Localizar: Localizar em sub-objetos pelo nome (sub-objetos: somente encontrar em filhos)
GetChild: Encontra objetos filho de acordo com o índice (objetos filho: busca somente na geração filho)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 功能:在层级未知的情况下,通过名字查找子物体的变换组件(是一个帮助类、工具 所以不用继承MonoBehaviour)
/// 作者:Dtc
/// </summary>
public class TransformHelper
{
/// <summary>
/// 通过名称获取 子物体变换组件
/// </summary>
/// <param name="parentTF">父物体的变换组件(即父物体)</param>
/// <param name="childName">要查找的孩子的名称</param>
/// <returns>查找到的物体</returns>
public static Transform GetChildByName(Transform parentTF, string childName)
{
//在子物体中查找
Transform childTF = parentTF.Find(childName);
//如果查找到对应的子物体则 返回该物体
if (childTF != null) return childTF;
#region 没查到将问题交给子物体
//没查到,则查找子物体的子物体(parentTF.GetChild(i):获取第 i+1 个子物体)
//childTF = GetChildByName(parentTF.GetChild(0), childName);
//if (childTF != null) return childTF;
//没查到,则查找子物体的子物体(parentTF.GetChild(1):获取第 2 个子物体)
//childTF = GetChildByName(parentTF.GetChild(1), childName);
//if (childTF != null) return childTF;
//以此类推 查找所有孩子 可通过循环来编写
#endregion
//获取子物体的数量,用于for循环遍历子物体
int count = parentTF.childCount;
for (int i = 0; i < count; i++)
{
childTF = GetChildByName(parentTF.GetChild(i), childName);
if (childTF != null) return childTF;
}
return null;//如果都没找到 则返回null
}
}