如何在没有 parent 的情况下获得所有 children?

How to get all children without the parent?

Transform[] drawns = GetComponentsInChildren<Transform>()

这也包括 parent 但我只想获取脚本连接的转换的 children。

问题是它在循环中也破坏了 parent。 抽奖数组中的第一项是 parent :

case DrawStates.DrawOnGizmosRuntime:
drawOnce = true;
if (line != null && drawOnGizmos == false)
{
    Transform[] drawns = GetComponentsInChildren<Transform>();
    if (drawns.Length > 0)
    {
        foreach (Transform drawn in drawns)
        {
            Destroy(drawn.gameObject);
        }
    }
}
if (boxCollider == null)
{
    boxCollider = boxColliderToDrawOn.GetComponent<BoxCollider>();
}
drawOnGizmos = true;
break;

实际上有几种方法可以在没有 parent 的情况下找到 children。

foreach (var child in children) Debug.Log(child);

使用扩展名:

使用system.linq后,可以将非原变换的children分开,如下图

var children = transform.GetComponentsInChildren<Transform>().Where(t => t != transform);

删除索引 0:

由于索引 0 始终是主要转换,因此您可以在将 children 转换为列表后将其删除。

var children = transform.GetComponentsInChildren<Transform>().ToList();

children.RemoveAt(0);

使用跳过(1)

感谢亲爱的@Enigmativity,另一种解决方案是使用Skip(1),这实际上避免了主要的变换成员。

var children = transform.GetComponentsInChildren<Transform>().Skip(1);