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

Unity笔记之查找子物体

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

Unity笔记之查找子物体

需求:通过类型和名字在某个物体里面找到满足这个条件的物体。
原因:unity原有的transform类提供的查找方法只能查找第一层级的子物体,想要找第二三层级的就比较麻烦。所以就只能自己拓展一个方法出来查找了。

举例:

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

public static class TransformHelper
{
    /// 
    /// 查找子物体(递归查找)  where T : UnityEngine.Object
    ///  
    /// 父物体
    /// 子物体的名称
    /// 找到的相应子物体
    public static T FindDeepTransform(this Transform trans, string targetName) where T : Component
    {
        Transform child = trans.Find(targetName);
        T t = null;
        if (child != null)
        {
            t = child.GetComponent();
            return t;
        }
        for (int i = 0; i < trans.childCount; i++)
        {
            Transform parent = FindDeepTransform(trans.GetChild(i), targetName);
            if (parent != null)
            {
                t = parent.GetComponent();
                return t;
            }
        }
        return t;
    }

    /// 
    /// 查找所有需要类型的子物体(具体查找逻辑交给单独的递归方法)
    /// 
    /// 需要查找的类型
    /// 父物体
    /// 查找的组件对应的名字
    /// 返回所有名字为targetName并且包含查找组件的组件
    public static List FindDeepTransforms(this Transform trans, string targetName) where T : Component
    {
        List t = new List();

        Find(trans, targetName, ref t);

        return t;
    }
    /// 
    /// 以递归的方式查找子物体,将指定类型的组件保存起来
    /// 
    /// 需要查找的类型
    /// 父物体
    /// 查找的组件对应的名字
    /// 找到相应物体
    private static void Find(Transform trans, string targetName, ref List t) where T : Component
    {
        int number = trans.childCount;
        while (number > 0)
        {
            for (int i = 0; i < trans.childCount; i++)
            {
                if (trans.GetChild(i).name == targetName)
                {
                    if (trans.GetComponent())
                        t.Add(trans.GetChild(i).GetComponent());
                }
                if (trans.GetChild(i).childCount > 0) Find(trans.GetChild(i), targetName, ref t);
                number--;
            }
        }
    }
}

/// 
/// 实现多个测试
/// 
public List obj = new List();
void Start()
{
	obj = transform.FindDeepTransforms("Cube");
}

里面提供了两个拓展方法,为了方便查找单个或者多个物体(不管是否激活都能找到)

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

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

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