Home > Mobile >  Check child count for the active child objects
Check child count for the active child objects

Time:11-15

I have a parent game object that has 20 child objects. Few of them are active and rest are inactive. How do I check my if statement for the 5 and less active child objects? Currently it is just counting the child count irrespective active/inactive state of them.

void Start () {

        //Active Child count

        if (this.transform.childCount <= 5) {

        }
}

CodePudding user response:

If you are into inq you could be unig e.g.

using System.Linq;

...

var count = transform.Cast<Transform>().Where(child => child.gameObject.activeSelf).Coun();

For whatever reason Transform only implements the generic IEnumerable so you first have to Cast the results from object into Transform again. Then you filter only those of active GameObjects and finally you Count those.


Or just use the explicit form

var count = 0
foreach(Transform child in transform)
{
    if(child.gameObject.activeSelf) count  ;
}

CodePudding user response:

To ckeck if the a GameObject is active or not use this line:

If(myGameObject.activeSelf)
  //Do something if myGameObject is active

You have 20 child so you need to loop through all the GameObjects and check if they are active or not.

public void checkActive()
    {
        int activeCounter = 0;
        for(int i = 0; i < parent.transform.childCount; i  )
        {
            if(parent.transform.GetChild(i).gameObject.activeSelf)
            {
                activeCounter  ;
            }
        }
        Debug.Log("active gameObjects = "   activeCounter);
    }
  • Related