类似目录的三种遍历方法

    /// <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;
    }
}

阅读更多

没有更多推荐了,返回首页