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
So, I imagine you are doing something like Code (csharp): foreach(Transform child in transform){ if(child.active) Count++; }
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; }
I know this post is pretty old but I got another simple solution. Just try: GetComponentsInChildren<Transform>().GetLength(0); Now it will only count active children. Best regards Robert
This works incorrect since it returns not only direct children, but all hierarchy recursive counting the object itself.
Actually this works very well. Just find another component that there is only one in a child. I mean <Transform> is very common component and could be in every layers of a child. In my case I used <NavMeshAgent> and it worked perfectly.
Thanks, Robert! For anyone like me who found this useful but doesn't quite understand how it works exactly, <T> 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 Code (CSharp): GetComponentsInChildren<Bullet>().GetLength(0); Hope this helps!