IndexOutOfRangeException: Index was outside the bounds of the array

ConsoleRuntime exception · Scripting

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

  1. The loop goes one step too far

    A loop written i <= array.Length runs once past the end. It should be i < array.Length.

  2. 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.

  3. 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

Fix
C#
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 written i <= array.Length runs one step past the end. Use i < 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. Log array.Length just 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 Count or Length.

Scripts that avoid it

Related errors

Got a different error? Paste it into the error lookup.