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

Unity根据子物体名字,寻找子物体的组件

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

Unity根据子物体名字,寻找子物体的组件

我们寻找子物体,一般需要知道每个子节点,例子如下:

比如说,我需要找到CloseButton这个物体上的按钮组件,脚本挂在Canvas上,如果是用平常的方式来寻找的话:

transform.Find("BG/Image/CloseButton").GetComponent

 需要使用这样一种方式来找寻,我觉得比较麻烦,于是写了一下遍历的工具。

先看代码:

using UnityEngine;

/// 
/// 
/// * Writer:June
/// *
/// * Data:2021.5.31
/// *
/// * Function:寻找物体的工具类
/// *
/// * Remarks:
/// 
/// 

namespace JuneLib.Utils
{
    public static class JuneTool
    {
        public static Transform FindMyChild(Transform parentTF, string childName)
        {
            //在子物体中查找
            Transform childTF = parentTF.Find(childName);
            if (childTF != null) return childTF;
            //将问题交由子物体
            int count = parentTF.childCount;
            for (int i = 0; i < count; i++)
            {
                childTF = FindMyChild(parentTF.GetChild(i), childName);
                if (childTF != null) return childTF;
            }
            return null;
        }

        public static Transform FindChildExpend(this Transform parentTF, string childName)
        {
            //在子物体中查找
            Transform childTF = parentTF.Find(childName);
            if (childTF != null) return childTF;
            //将问题交由子物体
            int count = parentTF.childCount;
            for (int i = 0; i < count; i++)
            {
                childTF = FindMyChild(parentTF.GetChild(i), childName);
                if (childTF != null) return childTF;
            }
            return null;
        }

        public static T FindChildCompomentExpend(this Transform parentTF, string childName)
        {
            return FindChildExpend(parentTF, childName).GetComponent();
        }

    }
}

这是一个静态工具类,后面两个方法是扩展方法,可以直接使用,非常方便:

使用工具后,方便很多,即使不知道目标物体的父物体,都可以查找,不过需要注意的是,字符串的名字别填错!!!还有就是不可滥用,在父子层级非常多,并且子物体非常多的时候,就性能而言,还是不推荐使用这个方法。

transform.FindChildCompomentExpend

 

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

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

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