using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindTools : MonoBehaviour
{
///
/// transform类型递归查找子物体
///
/// 返回需要查找的子物体.
/// 查找起点.
/// 需要查找的子物体名字.
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;
}
///
/// 泛型查找
///
/// 返回需要查找的子物体的类型.
/// 查找起点.
/// 需要查找的子物体名字.
/// The 1st type parameter.
public static T FindFunc(Transform parent,string targetName) where T:Component
{
Transform target = parent.Find(targetName);
if (target!=null)
{
return target.GetComponent();
}
for (int i = 0; i < parent.childCount; i++)
{
target = FindFunc(parent.GetChild(i), targetName);
if (target!=null)
{
return target.GetComponent();
}
}
return target.GetComponent();
}
}
2.使用 GetComponentsInChildren
遍历子物体
还有一个方法可以很简单的获取到子节点的所有物体,那就是GetComponentsInChildren()
.因为每个物体必定会有transform组件,所以这个方法可以巧妙的获取到所有的物体! 用法如下:
Transform[] allChild;
// Use this for initialization
void Start()
{
allChild = GetComponentsInChildren();
foreach (Transform child in allChild)
{
Debug.Log(child.name);
}
}
执行这段代码之后,就可以获取到了所有的子物体了,遍历的顺序是有子节点则遍历子节点,没有则遍历兄弟节点,这里是不是有点深度遍历的意思哈哈哈
result.png
3.实现遍历的一种思路
其实我在一开始还没有想到方法2的.......,而是想着自己去遍历,下面贴一下自己实现遍历Unity物体子节点的代码,或许以后面试会用到哈哈哈
// Use this for initialization
void Start()
{
GetAllChild(this.transform);
}
//使用队列实现
public void GetAllChild(Transform parent)
{
//队列存放需要被遍历的节点
//加入的逻辑为:当前节点的子节点,从第一个子节点到最后一个子节点顺序加入
Queue queue = new Queue();
queue.Enqueue(parent);
while (queue.Count > 0)
{
//当前访问的子节点
Transform current = queue.Dequeue();
//输出当前节点的名字
Debug.Log(current.name);
//如果当前节点有子节点,则将其加入队列,留待以后遍历
for (int i = 0; i < current.childCount; i++)
{
queue.Enqueue(current.GetChild(i));
}
}
}
结果如下,从输出的顺序大概就可以看到我遍历的思路了。
另外, transform.SetParent 比 transform.Parent 效率要高很多。
https://blog.csdn.net/yzx5452830/article/details/79787325?utm_medium=distribute.pc_relevant.none-task-blog-utm_term-2&spm=1001.2101.3001.4242 https://www.jianshu.com/p/b3b844efb329
https://blog.csdn.net/A_Pro_Cat/article/details/100557555