Checking through all gameObjects in an array and setting them to inactive.

I have triggers in my game that set gameObjects in an array to active from inactive using SetActive(true/false).
Some of these triggers have different amounts of gameObjects to make active than others.

Currently in my Start function I have these lines of code to set each gameObject attached to the trigger to SetActive(false):

        whatToTrigger[0].SetActive(false);
        whatToTrigger[1].SetActive(false);
        whatToTrigger[2].SetActive(false);

For triggers that have less than 3 gameObjects in their array it returns an exception because there isn’t always 3 gameObjects that need to be set to inactive.

What kind of code could I write that runs through each gameObject in an array, sets them all to inactive and then stops running once they have all been set?

I’ll be here to reply to any questions you have if I didn’t explain something well enough :slight_smile:

Thanks,
Corey

Try:

for(int i = 0; i < whatToTrigger.Length(); i++) {
        whatToTrigger[i].SetActive(false);}

You could also put this inside a function, like

private bool toggle = false;

public void ToggleObjects(bool toggleBool){
toggleBool = !toggleBool;
for(int i = 0; i < whatToTrigger.Length(); i++){
whatToTrigger[i].SetActive(toggleBool);}
}

and then when you want to toggle things on/off you just write:

ToggleObjects(toggle);

inside the function. Then it automatically alternates on/off.

1 Like

Thankyou very much, this helped me solve the problem :slight_smile:

Fun fact, that is called a “for loop” and if you type “for” and hit tab twice, your script editor will autocomplete it for you. That shortcut will be a dear friend to you in many situations.

I had no idea about that shortcut. That will come in handy.

Holy shit that’s amazing, I’ve dabbled with for loops before but not properly. That shortcut is going to make me want to use them more haha.