It is a GameObject array.
if(Input.GetKeyDown(KeyCode.A))
for (int i = levelArray.Length; i > 0; i–)
{
Debug.Log(levelArray[ i ].name);
}

![]()
Everyone always forgets the existence of 0. The poor number, so neglected :p.
Array.length tells you the number of items in the array, not the maximum index of the array.
i.e: an array with 8 items in it has a length of 8, but its maximum index is 7 (0, 1, 2, 3, 4, 5, 6, 7)
Starting i at levelArray.length then trying to access an item at aray index i, is out of bounds.
Subtract 1 from .length.
Also, change > 0 to >= 0, or you’ll miss the entry at index 0.
for (int i = levelArray.Length - 1; i >= 0; i--)
{
Debug.Log(levelArray[ i ].name);
}
The length of an array [‘a’,‘b’,‘c’] is 3. array[2] is ‘c’ but array[3] is out of range.
i’ve changed it to
if(Input.GetKeyDown(KeyCode.A))
for (int i = levelArray.Length; i >= 0; i–)
{
Debug.Log(levelArray[ i ].name);
}
still get

Because you’re still setting i to array.length then trying to access the array at index i.
Again, array.length doesn’t tell you the maximum index of the array it tells you the number of items in the array. The index always starts at 0. An array with 8 items has the indicies 0, 1, 2, 3, 4, 5, 6, 7. If you try to access index 8 (which is the arrays length) it’s out of bounds. You need to subtract 1 from length.
Ah okey it works now thanks you
forgot to type -1 before my bad
You should start using Try…Catch on your code.
Try
{
for (int i = levelArray.Length - 1; i >= 0; i--)
{
Debug.Log(levelArray[ i ].name);
}
}
Catch (Exception e)
{
Print(e.Message);
}
No, please don’t do that.
An IndexOutOfRangeException is something you never want to catch. Instead, fix the code so that it cannot occur.
Same applies for various exceptions that can generally be avoided, such as NullReferenceExceptions and the like.
I am a big fan of foreach now i dont know exactly what levelarray is but something similar to this approach might work:
Wrong, you must catch every error what client has able to do. For avoid doing the error you fix your code.
Uhh suddoha is correct. If you’re needing to wrap every single piece of code in try-catch then you’re writing extremely bad code. Try-catch is for handling exceptions in things that you can’t reliably control for, not a band aid for incorrectly written code.
If you wrap faulty code like the one you had above in a try-catch the for loop will just not be executed and the catch will always be executed. Very bad idea you could as well delete the loop.
You shouldn’t handle it. Just fix it. Many exceptions can be avoided using a proper defensive programming strategy and that’s usually the way to go. Do not randomly catch exceptions, instead do proper validation in the given context.
Happy coding though.