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

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

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

transform.Find("BG/Image/CloseButton").GetComponent<Button>();

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

先看代码:

using UnityEngine;

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

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<T>(this Transform parentTF, string childName)
        {
            return FindChildExpend(parentTF, childName).GetComponent<T>();
        }

    }
}

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

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

transform.FindChildCompomentExpend<Button>("CloseButton");

 

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值