Checking if all gameobjects in list are inactive

I need to check a list and DO SOMETHING once they ALL become INACTIVE, and DO NOTHING if even ONE of them is ACTIVE. By active i mean active in hierarchy (gameobject not disabled)

private List<Ball> balls;

public void SetUpBalls()
        {
            balls = new List<Ball>();
        }

The only way I could think of would be to iterate over the list and check each entry, but that would be very costly, if you would want to do that all the time. An example would be the following method:

bool AreAllBallsInactive(){
	foreach(Ball ball in balls) {
		 if(ball.activeSelf) {
			return false;
		 }
	}
	return true;
}

that uses ActiveSelf to check if a ball is active or not

The problem with iterating over everything is that it wouldn’t be very efficient, especially if you need to check it often or have a lot of entries in the list.

A better way would be to just call it once when you need to know it and that’s it. You could also use LinQ to essentially do the same, like for example:

List<Ball> activeBalls = balls.Where(ball => ball.activeSelf == true);
if(activeBalls.Count > 0) {
// there are some active balls
}
//or alternatively just check
activeBalls.Any(); //if it's true, it means that the activeBalls list contains something and thus not all balls are inActive

though it basically amounts to the same thing… iterating over everything to figure out if any of them are active

Just keep in mind that iterating that balls list isn’t something you should do super often (by that I mean, in an Update call)

You can use two list for this purpose to avoid costly iteration. You just need to take all active gameobjects in one list and whenever any gameobject inactive just remove it from the list and add in another list and vice-versa. By doing this you will can directly check if there is any element exists in inactive gameobjects list or not.

Or if you don’t care about costly iteration, you can search element by listname.Contains(gameobject) and then check if this gameobject is active in hierarchy or not by using gameobject.activeSelf.