测试-关于Unity获取子层级内容的几种接口(Transform FindChild, Component GetComponentInChildren,...)

测试常用的层级内组件查找接口,但一些需求还是需要扩展

比如按照名称批量查找节点等

 

1.Transform - Transform Find(string name)

可以直接根据名称搜索到子层级节点和孙节点等,支持非激活的节点,但不能返回数组

不支持搜索自身

var bTransform = transform.Find("a/b");
Debug.Log(bTransform);

 更正只支持对路径搜索,不支持子节点孙节点的字符匹配(测试unity5.6.2)

2.Transform - Transform FindChild(string name)

可以搜索到子节点,但不支持孙节点,曾孙节点等。支持非激活的节点

不支持搜索自身,出场率很低,基本用不到

var aTaransform = transform.FindChild("a");
Debug.Log(aTransform);

3.Component - T GetComponentInChildren<T>(bool includeInactive)

支持子节点,孙节点的搜索。

如果自身存在这个组件,可返回自身

如果是非激活的对象,第二个参数includeInactive设为true即可搜索到

但缺点是只能搜索组件,不能按照名称搜索

用GetComponentsInChildren可以搜索多个,返回数组

GetComponentInParent规则同此条

原文地址:https://www.cnblogs.com/hont/p/5719779.html