递归查找是我们在日常开发中很容易用到的一种查找方法,通常我们在开发中都直接将其封装为一个查找工具类,便于我们全局使用。接下来我就为大家详解一下递归查找子节点物体和对应组件的工具类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindTools : MonoBehaviour
{
/// <summary>
/// transform类型递归查找子物体
/// </summary>
/// <returns>返回需要查找的子物体.</returns>
/// <param name="parent">查找起点.</param>
/// <param name="targetName">需要查找的子物体名字.</param>
public static Transform FindFunc(Transform parent,string targetName)
{
Transform target = parent.Find(targetName);
//如果找到了直接返回
if (target != null)
return target;
//如果没有没有找到,说明没有在该子层级,则先遍历该层级所有transform,然后通过递归继续查找----再次调用该方法
for (int i = 0; i < parent.childCount; i++)
{
//通过再次调用该方法递归下一层级子物体
target = FindFunc(parent.GetChild(i), targetName);
if (target!=null)
return target;
}
ret