Count Only active child's

How can I count active child’s and get a int
transform.childCount will count all child’s on the object I only want it to count active one
so how can I do it

1 Like

So, I imagine you are doing something like

foreach(Transform child in transform){
if(child.active)
Count++;
}
1 Like

If you’re new to programming, it’s a good example of using a category (or “extension” as they are called in c#)

  • public static int ChildCountActive( this Transform t )
  • {
  • int k = 0;
  • foreach(Transform c in t)
  • {
  • if(c.gameObject.activeSelf)
  • k++;
  • }
  • return k;
  • }
3 Likes

I know this post is pretty old but I got another simple solution. Just try:

GetComponentsInChildren().GetLength(0);

Now it will only count active children.

Best regards
Robert

5 Likes

this works pretty well
Thanks

This works incorrect since it returns not only direct children, but all hierarchy recursive counting the object itself.

2 Likes

Heh, this worked very well to me, thanks!

Actually this works very well. Just find another component that there is only one in a child. I mean is very common component and could be in every layers of a child. In my case I used and it worked perfectly.

Thanks, Robert!

For anyone like me who found this useful but doesn’t quite understand how it works exactly, is the name of the component. It can even be a name of a scrip attached to your game object.

Example:
If your gameObject has 10 child objects under them, this would get 10 transform components (count = 10 instead of 1).
To avoid this, I’d get a single unique component (my bullet prefab has a “Bullet” script so I’d try GetComponentsInChildren<Bullet>().GetLength(0);

Hope this helps!

1 Like

Thank You!

Please use the like button to show appreciation instead of necro posting.
Thread locked

1 Like