I am a beginner C# coder, and I am trying to make a game in Unity. Hence the question: Can I check if all children of an object are active in a scene? I want to use it to check if all enemies are active.
Asked
Active
Viewed 4,901 times
2 Answers
4
You could check using:
for (int i = 0; i< gameObject.transform.childCount; i++)
{
if(!gameoObject.transform.GetChild(i).gameObject.activeInHierarchy)
{
return false;
}
}
return true;
activeInHierarchy
is exactly what you need.
2
Extending Johnny's answer
Since Transform
implements IEnumerable
iteratign through all children you can easier loop using foreach
foreach(var child in transform)
{
if(child.gameObject.activeInHierachy) continue;
return false;
}
return true;
Or using Linq Cast
and Linq All
using System.Linq;
bool allActive = transform.Cast<Transform>().All(child => child.activeInHierachy);

derHugo
- 83,094
- 9
- 75
- 115
-
is using `foreach` for iterating through all children faster or more efficient than `for loop`? – Richard Johnson Oct 21 '22 at 05:35
-
1@RichardJohnson afaik it should be about the same .. internally the [`GetEnumerator`](https://github.com/Unity-Technologies/UnityCsReference/blob/73c12b5a403abad9a300f01a81e7aaf30a0d30b5/Runtime/Transform/ScriptBindings/Transform.bindings.cs#L326) also basically uses a self incrementing index and `GetChild` .. it is just way easier to write ;) – derHugo Oct 21 '22 at 05:41