IndexOutOfRangeException: Index was outside the bounds of the array
IndexOutOfRangeException: Index was outside the bounds of the array.
Your code read or wrote array position i, and i was negative or not less than the array's Length. Arrays start at 0, so the last valid index is Length - 1.
Read the Console line first
The stack trace names the line. Log the index and the array's Length just before it to see which is wrong.
Common causes
The loop goes one step too far
A loop written i <= array.Length runs once past the end. It should be i < array.Length.
The array is empty
The array was sized in code but filled in the Inspector, or the Inspector list was left at size 0. Any index fails on an empty array.
A random index used the wrong bound
Random.Range(0, array.Length) is correct for integers, because the upper bound is exclusive. Random.Range(0, array.Length + 1) is not.
The fix
if (spawnPoints.Length == 0) return;
var point = spawnPoints[Random.Range(0, spawnPoints.Length)];Stop it coming back
Prefer foreach when you do not need the index, and check Length before picking from an array that is filled in the Inspector.
Questions
- Why does the loop fail on the last element?
- Array indices run from 0 to
Length - 1. A loop writteni <= array.Lengthruns one step past the end. Usei < array.Length, or a foreach loop when you do not need the index. - The Inspector shows the right size. Why is the array still too small?
- The code may replace it:
array = new int[3];in Awake discards the Inspector's array. Or the code reads the array before something fills it. Logarray.Lengthjust before the failing line to see the size the code actually has. - Is this the same error for List?
- No. Arrays throw IndexOutOfRangeException; List<T> throws ArgumentOutOfRangeException for the same mistake. The fix is the same: check the index against
CountorLength.
Scripts that avoid it
Related errors
Got a different error? Paste it into the error lookup.