user7564765
user7564765

Reputation:

UnityException: Transform child out of bounds

I have six panels were the current effects are showing. If the amount of effects is 0, I want all of them to disappear. The effectOff() deactives all panels and effect images. The six panels have each six children effect images. (blue, green, red etc.). The code should make all of them deactivated.

public GameObject effectbar;

public void effectOff()
{
    for (int i = 0; i < 6; i++)
    {
        for (int a = i; i < 6; i++)
        {
            effectbar.gameObject.transform.GetChild(i).GetChild(a).gameObject.SetActive(false);
        }
        effectbar.gameObject.transform.GetChild(i).gameObject.SetActive(false);
    }
    effectbar.SetActive(false);
}

The effectbar.gameObject.transform.GetChild(i).gameObject.SetActive(false); line gives a Transform child out of bounds exception. How do I fix that? I read that it throws an error because the system doesn't know if a children object really exists. Thanks forwards.

Upvotes: 2

Views: 11098

Answers (2)

josephmbustamante
josephmbustamante

Reputation: 352

Your inner loop is incrementing i, so that when the inner loop finishes i is 6, after which the call in your outer loop fires, but your i is now out of bounds.

You'll probably want either a different variable incrementing your inner loop, or something else that works depending on what you need.

Upvotes: 0

Deadzone
Deadzone

Reputation: 814

Assuming effectBar is the parent of all of your panels, you can write only this line:

effectbar.SetActive(false);

Because effectbar is the parent it will also deactivate the children automatically.

Upvotes: 3

Related Questions