递归查找是我们在日常开发中很容易用到的一种查找方法,通常我们在开发中都直接将其封装为一个查找工具类,便于我们全局使用。接下来我就为大家详解一下递归查找子节点物体和对应组件的工具类:
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;
}
return target;
}
/// <summary>
/// 泛型查找
/// </summary>
/// <returns>返回需要查找的子物体的类型.</returns>
/// <param name="parent">查找起点.</param>
/// <param name="targetName">需要查找的子物体名字.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static T FindFunc<T>(Transform parent,string targetName) where T:Component
{
Transform target = parent.Find(targetName);
if (target!=null)
{
return target.GetComponent<T>();
}
for (int i = 0; i < parent.childCount; i++)
{
target = FindFunc(parent.GetChild(i), targetName);
if (target!=null)
{
return target.GetComponent<T>();
}
}
return target.GetComponent<T>();
}
}
是不是很简单就搞定递归查找。
(小科普:很多人认为递归就是无限循环的执行,虽然表面上是这样,但是递归和死循环的区别在于:递归是有结束循环条件的,而死循环没有)