Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all children without the parent?

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;
like image 742
Daniel Lip Avatar asked Oct 18 '25 02:10

Daniel Lip


1 Answers

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);
like image 180
KiynL Avatar answered Oct 20 '25 15:10

KiynL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!