Need help with void to disable BoxCollider2D only in children of gameobject

Hi Guys,
I am trying to disable all the BoxCollider2D in the children of a gameobject. The code Im using is:

    private BoxCollider2D[] colliders;

    public void Enter(Tartaruga enemy)
    {
        this.enemy = enemy;
        DisableChildrenCollider();   

private void DisableChildrenCollider()
    {
        colliders = enemy.GetComponentsInChildren<BoxCollider2D>();
        for (int i = 0; i < colliders.Length; i++)
        {
            colliders[i].enabled = false;
        }
    }

This specific gameobject has a BoxCollider2D in itself, and also BoxCollider2Ds in children gameobjects.

What is happening is that the function is disabling the BoxCollider2D in the children gameobject but is ALSO disabling the BoxCollider2D in the gameobject itself.

What should I do to only disable the BoxCollider2D in the children, but not in the gameobject itself? I thought the GetComponentsInChildren would only return the colliders in the children objects, but looks like it also return the collider in the object itself.

Thx.

You could change your method like this:

private void DisableChildrenCollider()
    {
        colliders = enemy.GetComponentsInChildren<BoxCollider2D>();
        for (int i = 0; i < colliders.Length; i++)
        {
            if(colliders[i].transform != transform) {
                colliders[i].enabled = false;
            }
        }
    }
1 Like

Hi PGJ,
Thx very much for your answer. I also found another way for this in another thread, very similar to your suggestion.

    private void DisableChildrenCollider()
    {
        colliders = enemy.GetComponentsInChildren<BoxCollider2D>();
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject.transform.parent != null)
                {
                    colliders[i].enabled = false;
                }                   
        }
    }

Thx very much again and regards.