get first active child gameobject

I’m trying to find out how i can get the first active child gameobject from a parent for a couple of hours now.

Closest thing i came up with is this

                                        GameObject firstChild = transform.GetChild(0).gameObject;
                                        firstChild.SetActive(false);

But this returns the first gameObject even if it’s not active and i only need the first active one.

Is there any way to accomplish this?

4 Answers

4

//C#
GameObject firstActiveGameObject;

for (int i = 0; i < gameObject.transform.childCount; i++)
{
     if(gameObject.transform.GetChild(i).gameObject.activeSelf == true)
     {
           firstActiveGameObject = gameObject.transform.GetChild(i);
     }
}

This will set the first active child of a game object to the firstActiveGameObject variable.

As this was already reopened, you probably want to stop looping once you have found one so add a break statement in the if statement.

Note : you dont neeed "== true" activeSelf already a boolean

transform.GetComponentsInChildren()[1]

int i = 0;
while(i < transform.childCount){
if (transform.GetChild(i).gameObject.active){
// transform.GetChild(i) is the GameObject you want
}
i++;
}
// If the code reaches here, that means there is either no active child or no child at all. You have to handle this yourself.

i need help. "you cannot implicitly convert the type UnityEngine.Transform to UnityEngine.GameObject
@ivanparas ,I copied the code and it’s giving me an error. I’ve been trying this for two days in a row, could any1 help?
"You cannot convert the type “UnityEngine.Transform” in “UnityEngine.GameObject”
@allenallenallen @ivanparas

I'm not sure if this is going to be far too late, but the problem you are having is that you are missing a small bit off line 8: firstActiveGameObject = gameObject.transform.GetChild(i); It should actually read: firstActiveGameObject = gameObject.transform.GetChild(i).gameobject; you were just a layer too high up, looking at the transform of the parent, and not the gameobject(child).

firstActiveGameObject = Aincrad.transform.GetChild(i).gameObject; this one should work