C# 最底层的孩子

C# 最底层的孩子,c#,unity3d,C#,Unity3d,正如我所知,获取最顶端的父级是transform.root。如果我想要获取最底端的子级,并且在我不知道子级名称的情况下如何?我已经尝试过了 for (int i=0; i<theParent.childCount; i++) { int bottommost=theParent.childCount-1; Debug.Log(theParent.GetChild(bottommost).name); } for(int i=0;i首先,您需要定义什么是底部子级,因为子级的深度也可能

正如我所知,获取最顶端的父级是
transform.root
。如果我想要获取最底端的子级,并且在我不知道子级名称的情况下如何?我已经尝试过了

for (int i=0; i<theParent.childCount; i++) 
{
 int bottommost=theParent.childCount-1;
 Debug.Log(theParent.GetChild(bottommost).name);
}

for(int i=0;i首先,您需要定义什么是底部子级,因为子级的深度也可能取决于兄弟级

例如:

    • 儿童1
    • 儿童2
    • 儿童3
但是每个孩子都可以有自己的孩子

  • 儿童1
    • 儿童
    • 儿童1B
  • 儿童2
    • 儿童_2A
    • 儿童2B
    • 儿童英语2C
    • 儿童2D
    • 儿童2E
所以在这种情况下,所有孩子的孩子都处于同一水平

也许你指的是在编辑器中看到的最底层?
在这种情况下,可能会向nae中添加一些内容以搜索它…

创建父级变换下所有子级的列表

List<GameObject> list = new List<GameObject>();

foreach(Transform t in transform)
{
   list.Add(t.gameObject);

   if(t.childCount > 0)
     foreach(Transform c in t)
       list.Add(c);
}

如果希望子对象本身而不仅仅是变换,请执行以下操作:

int lastChildIndex = parentObject.transform.childCount - 1;
lastChildObject = parentObject.transform.GetChild(lastChildIndex).gameObject;
lastChild = transform.GetChild(transform.childCount - 1);
int lastChildIndex = parentObject.transform.childCount - 1;
lastChildObject = parentObject.transform.GetChild(lastChildIndex).gameObject;