通过Transform中的Find与GetChild相结合,运用递归算法,实现在层级未知情况下查找子物体的帮助类。(记录算法便于以后查看)
Find:根据名称在子物体中查找(子物体:只在儿子辈查找)
GetChild:根据索引查找子物体(子物体:只在儿子辈查找)
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
}
}