- Home /
2020 Unity. How do I set children of a parent object to be active?
I am making a game where the player can build structures. The buildings for the sake of my prototype have 5 stages. I am storing all stages in a custom ConditionsMet() function. it increases the stage number (Int) by 1, then using Debug.Log i confirm which stage the parent is in. The parent object is called BuildingFoundation, and the script is attached to this object. Attached to the object are 5 groups of objects (In this instance they each represent 5 walls, for each object group, at different heights) , which I have set as inactive for now. I want to, at each stage, set each group of objects to be active. stage 1 walls are active at stage 1, stage 2 deactivates stage one walls and activates stage 2 walls, stage 3 onwards copies the same function as stage 2. I already have the if statements set up, I just cant figure out how to set child group objects to be active without cluttering up my code (I am still learning C# at a beginner level) I tried gameobject.setactive(true) but this only works for what the script is attached to. Thank you in advance everyone, I am keen to further my learning and this would really help me understand more about parent child connections etc.
I want to add that i want the foundation object (the parent) to remain active throughout. i know that this doesnt need code cause its just an object. the foundation object is basically what i use to hold the script and locate the object in world.
Answer by HellsHand · Apr 07, 2021 at 12:56 PM
You could use a for loop to set each of the children active.
for (int i = 0; i < transform.childCount; i++)
{
transform.GetChild(i).gameObject.SetActive(true);
}
If they are nested children, you would need to activate the parent object first transform.GetChild(#).gameObject.SetActive(true);
you would use transform.GetChild(#).childCount
for the loops initialization and then in the loop would be transform.GetChild(#).GetChild(i).gameObject.SetActive(true);
where #
is the child's order in the hierarchy starting at 0.
transform.GetChild(#).gameObject.SetActive(true);
for (int i = 0; i < transform.GetChild(#).childCount; i++)
{
transform.GetChild(#).GetChild(i).gameObject.SetActive(true);
}
Answer by EliasMiettinen · Apr 07, 2021 at 01:47 PM
Also you can use a foreach loop as well.
foreach(Transform t in transform)
{
t.gameObject.SetActive(true);
}