我们寻找子物体,一般需要知道每个子节点,例子如下:
比如说,我需要找到CloseButton这个物体上的按钮组件,脚本挂在Canvas上,如果是用平常的方式来寻找的话:
transform.Find("BG/Image/CloseButton").GetComponent<Button>();
需要使用这样一种方式来找寻,我觉得比较麻烦,于是写了一下遍历的工具。
先看代码:
using UnityEngine;
/// <summary>
///
/// * Writer:June
/// *
/// * Data:2021.5.31
/// *
/// * Function:寻找物体的工具类
/// *
/// * Remarks:
///
/// </summary>
namespace JuneLib.Utils
{
public static class JuneTool
{
public static Transform FindMyChild(Transform parentTF, string childName)
{
//在子物体中查找
Transform childTF = parentTF.Find(childName);
if (childTF != null) return childTF;
//将问题交由子物体
int count = parentTF.childCount;
for (int i = 0; i < count; i++)
{
childTF = FindMyChild(parentTF.GetChild(i), childName);
if (childTF != null) return childTF;
}
return null;
}
public static Transform FindChildExpend(this Transform parentTF, string childName)
{
//在子物体中查找
Transform childTF = parentTF.Find(childName);
if (childTF != null) return childTF;
//将问题交由子物体
int count = parentTF.childCount;
for (int i = 0; i < count; i++)
{
childTF = FindMyChild(parentTF.GetChild(i), childName);
if (childTF != null) return childTF;
}
return null;
}
public static T FindChildCompomentExpend<T>(this Transform parentTF, string childName)
{
return FindChildExpend(parentTF, childName).GetComponent<T>();
}
}
}
这是一个静态工具类,后面两个方法是扩展方法,可以直接使用,非常方便:
使用工具后,方便很多,即使不知道目标物体的父物体,都可以查找,不过需要注意的是,字符串的名字别填错!!!还有就是不可滥用,在父子层级非常多,并且子物体非常多的时候,就性能而言,还是不推荐使用这个方法。
transform.FindChildCompomentExpend<Button>("CloseButton");