unity3d:遞歸查找子物體,並輸出路徑

static List<string> m_listPath = new List<string>();

    public static string GetChildPath(Transform trans, string childName)
    {
        m_listPath.Clear();
        FindChildGameObject(trans.gameObject, childName);
        string path = "";
        for (int i = 1; i < m_listPath.Count; i++)
        {
            path += m_listPath[i];
            if (i != m_listPath.Count-1)
                path += "/";
        }
        return path;
    }

    
    public static GameObject FindChildGameObject(GameObject parent, string childName)
    {
        m_listPath.Add(parent.name);
        if (parent.name == childName)
        {
            
            return parent;
        }
        if (parent.transform.childCount < 1)
        {
            return null;
        }
        GameObject obj = null;
        for (int i = 0; i < parent.transform.childCount; i++)
        {
            GameObject go = parent.transform.GetChild(i).gameObject;
            obj = FindChildGameObject(go, childName);
            if (obj != null)
            {
                
                break;
            }
        }
        
        return obj;
    }

如何使用

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

public class TestFindChild : MonoBehaviour
{
    public Transform m_par;
    public string m_childName;
    // Start is called before the first frame update
    void Start()
    {
        string path = PublicFunc.GetChildPath(m_par, m_childName);
        Debug.Log(path);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章