Unity通过名字寻找子物体

这是一个在Unity3D环境中使用的C#静态类TransformHelpers,包含了一个DeepFind方法,该方法通过递归方式查找Transform对象的任何子层级中的特定子物体。只需调用transform.DeepFind(Name),即可找到名为Name的子Transform。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

public static class TransformHelpers
{
    public static Transform DeepFind(this Transform TF, string childName)
    {
        Transform x = TF.Find(childName);//查找名字为childName的子物体
        if (x != null)
        {
            return x;
        }
        if (TF.childCount == 0)
        {
            return null;
        }
        for (int i = 0; i < TF.childCount; i++)
        {
            Transform childTF = TF.GetChild(i);
            x = DeepFind(childTF, childName);
            if (x != null)
            {
                return x;
            }
        }
        return null;
    }
}

由上所示,复制完脚本直接调用 transform.DeepFind(Name) 就可以找到了!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值