- Home /
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?
Answer by ivanparas · Jan 31, 2017 at 08:36 PM
//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.
Answer by allenallenallen · Jan 31, 2017 at 05:32 PM
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.
Answer by nerocraftmc4 · May 26, 2018 at 07:28 AM
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).
Your answer
![](https://koobas.hobune.stream/wayback/20220612110023im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I move both the parent and child to a known position where I want the child to be? 1 Answer
How to get the childrens tag from the parent GameObject? 1 Answer
How to hide GUI and chilren? 0 Answers
adding collider to a child object (script) 1 Answer
grandchild of an object not showing in prefab after apply 2 Answers