Unity中在层级位置情况下查找子物体

通过Transform中的Find与GetChild相结合,运用递归算法,实现在层级未知情况下查找子物体的帮助类。(记录算法便于以后查看)

Find:根据名称在子物体中查找(子物体:只在儿子辈查找)

GetChild:根据索引查找子物体(子物体:只在儿子辈查找)

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

/// <summary>
/// 功能:在层级未知的情况下,通过名字查找子物体的变换组件(是一个帮助类、工具 所以不用继承MonoBehaviour)
/// 作者:Dtc
/// </summary>
public class TransformHelper
{
    /// <summary>
    /// 通过名称获取 子物体变换组件
    /// </summary>
    /// <param name="parentTF">父物体的变换组件(即父物体)</param>
    /// <param name="childName">要查找的孩子的名称</param>
    /// <returns>查找到的物体</returns>
    public static Transform GetChildByName(Transform parentTF, string childName)
    {
        //在子物体中查找
        Transform childTF = parentTF.Find(childName);
        //如果查找到对应的子物体则  返回该物体
        if (childTF != null) return childTF;

        #region 没查到将问题交给子物体
        //没查到,则查找子物体的子物体(parentTF.GetChild(i):获取第 i+1 个子物体)
        //childTF = GetChildByName(parentTF.GetChild(0), childName);
        //if (childTF != null) return childTF;

        //没查到,则查找子物体的子物体(parentTF.GetChild(1):获取第 2 个子物体)
        //childTF = GetChildByName(parentTF.GetChild(1), childName);
        //if (childTF != null) return childTF;
        //以此类推  查找所有孩子  可通过循环来编写
        #endregion
        //获取子物体的数量,用于for循环遍历子物体
        int count = parentTF.childCount;
        for (int i = 0; i < count; i++)
        {
            childTF = GetChildByName(parentTF.GetChild(i), childName);
            if (childTF != null) return childTF;
        }
        return null;//如果都没找到 则返回null
    }

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值