void Start()
{
var allchildren = AddDescendantsWithTag(transform);
}
和
private List<GameObject> AddDescendantsWithTag(Transform parent)
{
List<GameObject> list = new List<GameObject>();
foreach (Transform child in parent)
{
list.Add(child.gameObject);
AddDescendantsWithTag(child);
}
return list;
}
但是它仅返回父级下一级的子级。
我想循环到最后。
该脚本已附加到transform上,并且transform也是父级。
答案 0 :(得分:3)
您正在反复分配一个新列表,然后将其丢弃。您可能只想分配一个列表并添加到列表中。试试这个:
void Start()
{
var allchilds = new List<GameObject>();
AddDescendantsWithTag(transform, allchilds);
}
private void AddDescendantsWithTag(Transform parent, List<GameObject> list)
{
foreach (Transform child in parent)
{
list.Add(child.gameObject);
AddDescendantsWithTag(child, list);
}
}
答案 1 :(得分:2)
进行递归调用时,您将丢弃该值,以使信息不会传递回递归。这很容易解决。
private List<GameObject> AddDescendantsWithTag(Transform parent)
{
List<GameObject> list = new List<GameObject>();
foreach (Transform child in parent)
{
list.Add(child.gameObject);
list.AddRange(AddDescendantsWithTag(child));
}
return list;
}