Search Unity

Transform Child out of bounds

Discussion in 'Scripting' started by Skyfall106, Sep 25, 2019.

  1. Skyfall106

    Skyfall106

    Joined:
    Mar 5, 2017
    Posts:
    132
    Hello everyone, hope you are having a nice day!

    I have an inventory script that gets all of the slots in the slotholder object, but it pumps out an error:

    UnityException: Transform child out of bounds

    I can not for the life of me figure out what is causing this error, So I am asking for help, if you need more information, ask me.

    Code (CSharp):
    1. for (int i = 0; 1 < slots; i++)
    2.         {
    3.  
    4.             // Detecting all slots that are child of the slot holder.
    5.  
    6.             slot[i] = slotHolder.transform.GetChild(i);
    7.         }
     
  2. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    493
    What is your "slots" variable?

    In your case, the "slots" variable is larger than the actual size of the "slot" array. You are basically trying to access a place in the array that does not exist. Also, where are you reducing the size of the "slots" variable? Your loop will go until 1 < slots, which in the case you've shown will be never (since slots value never changes) or always (in which case it won't even enter the loop).

    Instead of using the "slots" variable, try using slot.Length
     
  3. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,331
    You can use Transform.childCount to get the number of children that slotHolder has.

    Code (CSharp):
    1. for(int i = 0; i < slotHolder.transform.childCount; i++)
    2. {
    3.     slot[i] = slotHolder.transform.GetChild(i);
    4. }
     
  4. Vega4Life

    Vega4Life

    Joined:
    Nov 27, 2012
    Posts:
    17
    Another option that takes care of bounds for you is just to just a foreach on the transform:

    Code (CSharp):
    1.         foreach (Transform child in transform)
    2.         {
    3.             // Do things
    4.         }
     
    SisusCo likes this.
  5. Skyfall106

    Skyfall106

    Joined:
    Mar 5, 2017
    Posts:
    132
    This is what I was going to do, because it is what i did for other c# projects outside of unity, but I had trouble getting it to work, thank you for your help :)