我怎么能循环孩子的所有孩子?

在我添加的脚本的顶部:

public Transform parentToSearch; 

然后:

 private void OnGUI() { if (hasDescription == true && clickForDescription == true) { foreach (Transform child in parentToSearch) { if (child.GetComponent<ItemInformation>() != null) { ItemInformation iteminformation = child.GetComponent<ItemInformation>(); if (child.name == objectHit) { var centeredStyle = GUI.skin.GetStyle("Label"); centeredStyle.alignment = TextAnchor.UpperCenter; GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 25, 100, 50), iteminformation.description, centeredStyle); } } } } } 

但是当我做循环:

 foreach (Transform child in parentToSearch) 

它会find第一个父母的一级孩子,但是这个孩子也有孩子等等。 我想循环下所有的孩子的孩子和孩子。

例如在层次结构中,我有:

  • testing
    • testing1
    • TEST2
    • TEST3
      • Test31
      • Test32
    • TEST4
    • TEST5
      • Test51

所以现在它只会循环testing1,2,3,4,5,但我也想循环通过Test31,Test32,Test51

您可以使用recursion调用

 void Process(Transform parent, int level = 0) { // TODO: process the parent object. foreach (Transform child in parent) { // The Process method calls itself. This is the recursive call. Process(child, level + 1); } } 

您不必处理孩子,因为每个孩子都将成为recursion调用中的父代。

我还添加了一个级别信息,允许您打印时缩进儿童,添加标签等(可选)。


如果您不想处理顶级父级,则可以改为处理子级。

 void Process(Transform parent, int level = 0) { foreach (Transform child in parent) { // TODO: process the child object. // Process next deeper level Process(child, level + 1); } } 

适用于你的问题:

 private void OnGUI() { if (hasDescription && clickForDescription) { ProcessOnGUI(parentToSearch); } } void ProcessOnGUI(Transform parent, int level = 0) { foreach (Transform child in parent) { var iteminformation = child.GetComponent<ItemInformation>(); if (iteminformation != null && child.name == objectHit) { var centeredStyle = GUI.skin.GetStyle("Label"); centeredStyle.alignment = TextAnchor.UpperCenter; GUI.Label(new Rect( Screen.width / 2 - 50 + 20 * level, // <== INDENTATION Screen.height / 2 - 25, 100, 50), iteminformation.description, centeredStyle); } // Process next deeper level ProcessOnGUI(child, level + 1); } }