Check if multiple gameobjects are active

Hey there, Im currently writing a script that checks if multiple gameobjects are not active. If any are active I want it to keep checking if there are all inactive I want to do something else.

So far I have: (I know this checks if they are active not inactive which is wrong)

while (cleanBool == false)
        {
            //Needs to be inactive not active CHANGE!!!
            if(check01.activeInHierarchy && check02.activeInHierarchy && check03.activeInHierarchy && check04.activeInHierarchy && check05.activeInHierarchy)
            {
                cleanBool = true;
            }
            else
            {
                return null;
            }
        }

Is this a terrible way of doing it? Or is there a better way?

Thanks

Well ideally you don’t want to keep checking forever if all the gameObjects are active/inactive.

I would only check once one of the gameObject becomes inactive by using OnDisable().

Quick Example

This would be the parent object which contains the script with the function that checks if all objects are inactive.

using UnityEngine;
using System.Collections;

public class CheckIt : MonoBehaviour {

    public GameObjScript[] gameObjArray;

    public void Start()
    {
        PopulateGameObjArray();
    }

    void PopulateGameObjArray()
    {
        gameObjArray = GetComponentsInChildren<GameObjScript>();
    }

    public void CheckObjStatus()
    {
        if(AreAllGameObjInactive())
        {
            print ("All are inactive? Do something!");
        }
        else
        {
            print ("one of the object is active");
        }
    }

    bool AreAllGameObjInactive()
    {
        foreach(GameObjScript gameObj in gameObjArray)
        {
            if(gameObj.gameObject.activeInHierarchy)
            {
                return false;
            }
        }
        return true;
    }
}

Attach this to the GameObject that will be checked if active/inactive

using UnityEngine;
using System.Collections;

public class GameObjScript : MonoBehaviour
{

    CheckIt parentScript;

    void Awake()
    {
        parentScript = transform.GetComponentInParent<CheckIt>();
    }

    void OnDisable()
    {
        parentScript.CheckObjStatus();
    }
}

You can quickly test this by:

  • Putting an empty gameObject on the scene. Attach the first script to it.
  • Adding X amount of cubes inside the empty gameObject and attach the second script to them.
1 Like

Oh brilliant. Thanks for the great explanation. Really appreciate it :smile: