前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >unity3d:查找子物体,并输出路径,GetComponentsInChildren,递归查找,栈查找

unity3d:查找子物体,并输出路径,GetComponentsInChildren,递归查找,栈查找

作者头像
立羽
发布2023-08-24 15:02:36
发布2023-08-24 15:02:36
1.1K00
代码可运行
举报
文章被收录于专栏:Unity3d程序开发Unity3d程序开发
运行总次数:0
代码可运行

分为两步: 1.找到子物体的transform 2.通过child.parent = root,输出路径

找到子物体的transform

有三种方法:GetComponentsInChildren,递归查找,栈查找

GetComponentsInChildren

代码语言:javascript
代码运行次数:0
复制
foreach (Transform t in check.GetComponentsInChildren<Transform>())
{
    if (t.name == name)
    {
        Debug.Log("得到最终子物体的名字是:" + t.name);
        forreturn = t;
        return t;
    }
}

递归

代码语言:javascript
代码运行次数:0
复制
static Transform SearchNodeByRecursion(Transform tree, string valueToFind)
    {
        if (tree.name == valueToFind)
        {
            return tree;
        }
        else
        {
            if (tree.childCount > 0)
            {
                for (int i = 0; i < tree.childCount; i++)
                {
                    var temp = SearchNodeByRecursion(tree.GetChild(i), valueToFind);
                    if (temp != null) return temp;
                }

            }
        }
        return null;
    }

代码语言:javascript
代码运行次数:0
复制
static Transform SearchNodeByStack(Transform rootNode, string valueToFind)
    {
        var stack = new Stack<Transform>(new[] { rootNode });
        while (stack.Count > 0)
        {
            var n = stack.Pop();
            if (n.name == valueToFind)
            {
                //出栈,如果找到目标返回
                return n;
            }

            //当前节点还有child,全部入栈
            if (n.childCount > 0)
            {
                for (int i = 0; i < n.childCount; i++)
                {
                    stack.Push(n.GetChild(i));
                }
            } 
        }

        //栈为0还没找到
        return null;
    }

输出路径

代码语言:javascript
代码运行次数:0
复制
string GetChildPath(Transform check, string name)
    {
        List<string> listPath = new List<string>();
        string path = "";
        Transform child = GetTransform(check, name);
        Transform parent = child.parent;
        if (child != null)
        {
            listPath.Add(child.name);
            while (parent != null && parent != check )
            {
                listPath.Add(child.parent.name);
                parent = parent.parent;
            }
        }
        listPath.Add(check.name);

        for (int i = listPath.Count-1; i>= 0; i--)
        {
            path += listPath[i];
            if (i != 0)
            {
                path += "/";
            }
        }

        return path;
    }

源码

https://github.com/luoyikun/UnityForTest FindChild场景

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 找到子物体的transform
    • GetComponentsInChildren
    • 递归
  • 输出路径
  • 源码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档