1问题:在用到GetComponentsInChildren 方法的时候
如果GetComponentsInChildre
父对象和子对象以及孙物体都存在相同的T,那么这个得到的数组也会包含父子孙中的T
那么如何解决这个问题呢?
2解决方法:想象大家各有各的解决方法,名字区分,隐藏处理,foreach动态删除等等等等.......
这里我参考了Unity 关于GetComponentsInChildren 利用扩展方法如何避免获取父物体_Zero_LJ的博客-CSDN博客的扩展方法 发现这位博主的扩展方法并不能剔除孙物体,我在这里进行了优化。
1:首先创建一个BSGExtension类,然后写两个方法
2:再使用transform.GetComponentsInRealChildren
3:即可获得符合要求的子物体。
这里同时也制作了隐藏子物体的获取。只需要在参数里面传个true
获得子物体+隐藏子物体版本就ok了。
还在等什么快去试试吧。
最后贴上代码!
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
//扩展方法 值获取子物体上的T
public static class BSGExtension
{
public static T[] GetComponentsInRealChildren(this GameObject go, bool includeInactive = false) where T : Component
{
List TList = go.GetComponentsInChildren(includeInactive).ToList();
List TListReal = new List();
for (int i = 0; i < TList.Count; i++)
{
if (TList[i].transform.parent == go.transform)
{
TListReal.Add(TList[i]);
}
}
return TListReal.ToArray();
}
public static T[] GetComponentsInRealChildren(this Transform go, bool includeInactive = false) where T : Component
{
List TList = go.GetComponentsInChildren(includeInactive).ToList();
List TListReal = new List();
for (int i = 0; i < TList.Count; i++)
{
if (TList[i].transform.parent == go.transform)
{
TListReal.Add(TList[i]);
}
}
return TListReal.ToArray();
}
}



