Unity获取物体下的子物体+只获取子物体

1问题:在用到GetComponentsInChildren 方法的时候

如果GetComponentsInChildre<T>(),

父对象和子对象以及孙物体都存在相同的T,那么这个得到的数组也会包含父子孙中的T

那么如何解决这个问题呢?

 

 

  2解决方法:想象大家各有各的解决方法,名字区分,隐藏处理,foreach动态删除等等等等.......

这里我参考了Unity 关于GetComponentsInChildren 利用扩展方法如何避免获取父物体_Zero_LJ的博客-CSDN博客的扩展方法 发现这位博主的扩展方法并不能剔除孙物体,我在这里进行了优化。

1:首先创建一个BSGExtension类,然后写两个方法

 2:再使用transform.GetComponentsInRealChildren<T>();   方法

 3:即可获得符合要求的子物体。

 

这里同时也制作了隐藏子物体的获取。只需要在参数里面传个true

 

获得子物体+隐藏子物体版本就ok了。

 

还在等什么快去试试吧。

最后贴上代码!

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

//扩展方法 值获取子物体上的T 
public static class BSGExtension
{
    public static T[] GetComponentsInRealChildren<T>(this GameObject go, bool includeInactive = false) where T : Component
    {
        List<T> TList = go.GetComponentsInChildren<T>(includeInactive).ToList(); 
        List<T> TListReal = new List<T>();
        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<T>(this Transform go, bool includeInactive = false) where T : Component
    {
        List<T> TList = go.GetComponentsInChildren<T>(includeInactive).ToList();
        List<T> TListReal = new List<T>();
        for (int i = 0; i < TList.Count; i++)
        {
            if (TList[i].transform.parent == go.transform)
            {
                TListReal.Add(TList[i]);
            }
        }
        return TListReal.ToArray();
    }
} 

  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值