Soxehe
Soxehe

Reputation: 57

Check active state of gameObject in List

I have 4 gameObjects in a List. I would like to check the count of active gameObjects from this list. As in if two gameObjects are active, that means count is 2. How would be the best way to get the count?

public List<GameObject> Total_GO;

public void Start()
{
  //Get Count of active gameObjects
}

Upvotes: 0

Views: 860

Answers (1)

derHugo
derHugo

Reputation: 90630

You can simply use Linq Count and as a filter use GameObject.activeInHierarchy or GameObject.activeSelf according to your needs

using System.Linq;

...

void Start()
{
                             // or obj.activeSelf according to your needs
    var activeCount = Total_GO.Count(obj => obj.activeInHierarchy);

    Debug.Log($"Active objects: {activeCount}", this);
}

or if you rather want to actually use the active objects use Linq Where

 void Start()
{
                         // or obj.activeSelf according to your needs
    var activeObjects = Total_GO.Where(obj => obj.activeInHierarchy).ToList();
                             
    var activeCount = activeObjects.Count;
    Debug.Log($"Active objects: {activeCount}", this);

    foreach(var obj in activeObjects)
    {
        ...
    }
}

Upvotes: 2

Related Questions