类似目录的三种遍历方法

    /// <summary>
    ///  广度遍历
    /// </summary>
    /// <param name="tf"></param>
    /// <returns></returns>
    List<Transform> FindChildRecursion1(Transform tf)
    {
        List<Transform> allTf = new List<Transform>();
        Queue<Transform> parent = new Queue<Transform>();
        if (tf == null) return allTf;
        allTf.Add(tf);
        if (tf.childCount == 0)
        {
            return allTf;
        }
        parent.Enqueue(tf);
        Transform currentTf;
        while (parent.Count != 0)
        {
            currentTf = parent.Dequeue();
            for (int i = 0; i < currentTf.childCount; i++)
            {
                var child = currentTf.GetChild(i);
                allTf.Add(child);
                if (child.childCount != 0)
                {
                    parent.Enqueue(child);
                }
            }
        }
        return allTf;
    }
    /// <summary>
    /// 递归深度遍历
    /// </summary>
    /// <param name="tf"></param>
    /// <returns></returns>
    List<Transform> FindChildRecursion2(Transform tf)
    {
        List<Transform> allTf = new List<Transform>();
        if (tf == null) return allTf;
        allTf.Add(tf);
        if (tf.childCount == 0)
        {
            return allTf;
        }
        for (int i = 0; i < tf.childCount; i++)
        {
            allTf.AddRange(FindChildRecursion2(tf.GetChild(i)));
        }
        return allTf;
    }

    /// <summary>
    /// 非递归深度遍历
    /// </summary>
    /// <param name="tf"></param>
    /// <returns></returns>
    List<Transform> FindChildRecursion3(Transform tf)
    {
        List<Transform> allTf = new List<Transform>();
        if (tf == null) return allTf;
        allTf.Add(tf);
        if (tf.childCount == 0)
        {
            return allTf;
        }
        Transform currenttf = tf;
        Transform parnet = tf.parent;
        int childIndex = 0;
        while (currenttf != parnet)
        {
            while (childIndex < currenttf.childCount)
            {
                var tmpCurrenttf = currenttf.GetChild(childIndex);
                allTf.Add(tmpCurrenttf);
                if (tmpCurrenttf.childCount != 0)
                {
                    currenttf = tmpCurrenttf;
                    childIndex = 0;
                }
                else
                {
                    childIndex++;
                }
            }

            childIndex = currenttf.GetSiblingIndex() + 1;
            currenttf = currenttf.parent;
        }
        return allTf;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值