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()
{
}
}
結果