【递归】以递归查找子物体为例,优化递归写法

文章介绍了递归在查找Unity游戏对象子物体时可能导致的性能问题,提出使用堆栈优化的解决方案,包括递归写法和堆栈遍历方法,以及在完整代码中的应用。

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

1. 递归

函数体逻辑包含调用自身的函数,称为递归函数

但是!!

如果数据量比较大,短时间内可能会造成函数不断压栈,浪费性能。

递归可以理解成一个死循环,当不满足条件时,停止循环

所以这里提供一个堆栈写法,来优化递归

2. 查找子物体

2.1 递归写法

private Transform FindChild(Transform root, string childName)
{
    var trans = root.Find(childName);
    if (trans != null)
        return trans;

    if (root.childCount != 0)
    {
        for (int i = 0; i < root.childCount; i++)
        {
            trans = FindChild(root.GetChild(i), childName);
            if (trans != null)
                return trans;
        }
    }

    return null;
}

2.2 堆栈写法

Stack<Transform> stack = new Stack<Transform>();

private Transform FindChild2(Transform root, string childName)
{
    stack.Push(root);
    while (stack.Count > 0)
    {
        root = stack.Pop();

        var trans = root.Find(childName);
        if (trans != null)
            return trans;

        for (int i = 0; i < root.childCount; i++)
        {
            stack.Push(root.GetChild(i));
        }
    }

    return null;
}

总结:一遍逻辑,操作入栈

3. 完整代码

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

public class TransformUtility : MonoBehaviour
{
    void Start()
    {
        var res = FindChild2(transform, "Image (1)");
        if (res != null)
        {
            Debug.LogError("找到了 Image (1)");
            Debug.LogError($"{res.name}");
        }
    }

    private Transform FindChild(Transform root, string childName)
    {
        var trans = root.Find(childName);
        if (trans != null)
            return trans;

        if (root.childCount != 0)
        {
            for (int i = 0; i < root.childCount; i++)
            {
                trans = FindChild(root.GetChild(i), childName);
                if (trans != null)
                    return trans;
            }
        }

        return null;
    }

    Stack<Transform> stack = new Stack<Transform>();

    private Transform FindChild2(Transform root, string childName)
    {
        stack.Push(root);
        while (stack.Count > 0)
        {
            root = stack.Pop();

            var trans = root.Find(childName);
            if (trans != null)
                return trans;

            for (int i = 0; i < root.childCount; i++)
            {
                stack.Push(root.GetChild(i));
            }
        }

        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值