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?
//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.
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