栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

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

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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();
    }
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/897835.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号