Home > Blockchain >  How to get all children without the parent?
How to get all children without the parent?

Time:06-01

Transform[] drawns = GetComponentsInChildren<Transform>()

This include also the parent but i want to get only the children of the transform the script is connected.

The problem is that it's destroying in the loop also the parent. The first item in the array of drawns is the 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;

CodePudding user response:

There are actually several ways to find children without parent.

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

Use Where extension:

After using system.linq, you can separate children that are not the original transform, as shown below.

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

Removing index 0:

Since index 0 is always the main transform, you can delete it after converting children to list.

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

children.RemoveAt(0);

Using Skip(1)

Thanks to dear @Enigmativity, Another solution is to use Skip(1), which actually avoids the main transform member.

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