Mask or fix intentional out of bounds error

Hello, i’m trying to put all the chairs, under the GameObject this script is attached to, into a list. I want to make the amount of chairs vary, so i can’t drag them into the list in Unity.
when i run the game it says:

UnityException: Transform child out of bounds
ChairRegistry.Start () (at Assets/Scripts/ChairRegistry.cs:13)

I know it would be out of bounds, that’s when i want the script to stop. And it’s not a major issue, but the more i have of these errors, the harder it will be to find the actual errors.

Help would be much appriciated

the code i have problems with is the following:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChairRegistry : MonoBehaviour
{
    public List<GameObject> chairObject;

    // Start is called before the first frame update
    void Start()
    {
        int chairCount = 0;
        while ( transform.GetChild(chairCount).transform)
        {
            GameObject objectfound = transform.GetChild(chairCount).gameObject;
            chairObject.Add(objectfound);
            chairCount += 1;
        }
    }

There are much better ways to loop through the children of a transform than intentionally throwing an exception! Here’s a couple examples:

foreach (Transform child in transform) {
  GameObject objectfound = child.gameObject;
  chairObject.Add(objectfound);
  // etc...
}
for (int i = 0; i < transform.childCount; i++) {
  Transform child = transform.GetChild(i);
  GameObject objectfound = child.gameObject;
  chairObject.Add(objectfound);
  // etc...
}
2 Likes

You can catch errors and stop them with a try … catch block, but relying on this as a way of terminating your loop is generally a bad idea when you have other options. (It’s bad because it’ll also “catch” unintentional exceptions, causing things to fail silently.) And you do have other options!

If your chairs have a script on them (and, if they’re being used as participants in the game as they seem to be, they probably should), use GetComponentsInChildren(), and loop through the array that returns. (Adding a script to your chairs won’t cause performance problems as long as you remove the empty Start() and Update() methods from it)

This also will loop through all children of a transform, but I’d recommend this only if the above isn’t an option for some reason - if you ever add non-chair objects into the hierarchy, that will mess up this approach.

foreach (Transform child in transform) {
chairObject.Add(child.gameObject);
}
      while (chairCount <transform.childCount)
        {
            GameObject objectfound = transform.GetChild(chairCount).gameObject;
            chairObject.Add(objectfound);
            chairCount += 1;
        }

Ty for your response! <3