需求:通过类型和名字在某个物体里面找到满足这个条件的物体。
原因:unity原有的transform类提供的查找方法只能查找第一层级的子物体,想要找第二三层级的就比较麻烦。所以就只能自己拓展一个方法出来查找了。
举例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class TransformHelper
{
///
/// 查找子物体(递归查找) where T : UnityEngine.Object
///
/// 父物体
/// 子物体的名称
/// 找到的相应子物体
public static T FindDeepTransform(this Transform trans, string targetName) where T : Component
{
Transform child = trans.Find(targetName);
T t = null;
if (child != null)
{
t = child.GetComponent();
return t;
}
for (int i = 0; i < trans.childCount; i++)
{
Transform parent = FindDeepTransform(trans.GetChild(i), targetName);
if (parent != null)
{
t = parent.GetComponent();
return t;
}
}
return t;
}
///
/// 查找所有需要类型的子物体(具体查找逻辑交给单独的递归方法)
///
/// 需要查找的类型
/// 父物体
/// 查找的组件对应的名字
/// 返回所有名字为targetName并且包含查找组件的组件
public static List FindDeepTransforms(this Transform trans, string targetName) where T : Component
{
List t = new List();
Find(trans, targetName, ref t);
return t;
}
///
/// 以递归的方式查找子物体,将指定类型的组件保存起来
///
/// 需要查找的类型
/// 父物体
/// 查找的组件对应的名字
/// 找到相应物体
private static void Find(Transform trans, string targetName, ref List t) where T : Component
{
int number = trans.childCount;
while (number > 0)
{
for (int i = 0; i < trans.childCount; i++)
{
if (trans.GetChild(i).name == targetName)
{
if (trans.GetComponent())
t.Add(trans.GetChild(i).GetComponent());
}
if (trans.GetChild(i).childCount > 0) Find(trans.GetChild(i), targetName, ref t);
number--;
}
}
}
}
////// 实现多个测试 /// public Listobj = new List (); void Start() { obj = transform.FindDeepTransforms ("Cube"); }
里面提供了两个拓展方法,为了方便查找单个或者多个物体(不管是否激活都能找到)



