Quick answer: A List<T> was read or changed at an index that is below 0 or not below its Count. The first stack frame that points into Assets/ is the line to fix. The usual causes are an empty list, a loop that runs to Count inclusive, RemoveAt inside a forward loop, an index of -1 from IndexOf, and an index saved before the list shrank. Compare the index with Count before using it and log both when the check fails.
The Console shows ArgumentOutOfRangeException: Index was out of range, and the message tells you neither which list nor which index. That information is in the stack trace and in two numbers you have to log yourself: the index and the list’s Count. This guide shows how to read the trace down to the line, how to tell the common causes apart from those two numbers, and the code for each fix, ending with a small guard helper for indexes that come from saves, UI or the network.
- The exact error
- Lists throw this one, arrays throw another
- What causes it
- How to find the line and the cause
- Fix 1: check Count before you index
- Fix 2: correct the loop, and remove items backward
- Fix 3: make computed indexes land inside the list
- Fix 4: validate indexes that arrive from somewhere else
- How to confirm the fix
- What a report from a player’s machine tells you
- Related guides
- Frequently asked questions
The exact error
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <...>:0)
WaypointPatrol.Update () (at Assets/Scripts/WaypointPatrol.cs:31)
List`1[T].get_Item is the square-bracket read, list[i]. A write shows set_Item, and RemoveAt shows its own name. Some Unity versions print one or two System.ThrowHelper frames above the List`1 line. Skip them. Where this page shows <...>, Unity prints a long hex id for the library, which can be ignored.
The valid indexes of a list are 0 to Count - 1. “Must be non-negative” covers an index below zero, and “less than the size of the collection” covers an index equal to or above Count. The message is the same for both, and it does not include the value. It is a standard .NET exception, so it behaves the same in the editor, in Mono builds and in IL2CPP builds.
Lists throw this one, arrays throw another
If your message is close to this one but not identical, the wording tells you which call failed:
| Call | What Unity prints when the index is out of range |
|---|---|
list[i], list.RemoveAt(i) | ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. with Parameter name: index |
list.Insert(i, x) | ArgumentOutOfRangeException: Index must be within the bounds of the List. with Parameter name: index |
list.GetRange(i, n), list.RemoveRange(i, n) | ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. |
array[i] | IndexOutOfRangeException: Index was outside the bounds of the array. |
text.Substring(start, length) | ArgumentOutOfRangeException: Index and length must refer to a location within the string. with Parameter name: length |
text.Substring(start) | ArgumentOutOfRangeException: startIndex cannot be larger than length of string. with Parameter name: startIndex |
text.Remove(start, count) | ArgumentOutOfRangeException: Index and count must refer to a location within the string. with Parameter name: count |
transform.GetChild(i) | UnityException: Transform child out of bounds |
Insert accepts one more index than the indexer does: inserting at Count appends, and only Count + 1 or a negative value throws. The array version is covered in What Does “Index was outside the bounds of the array” Mean? (and How to Fix It). The causes below apply to both, and the string rows are the same mistake made with character positions.
What causes it
- The list is empty.
spawnPoints[0]throws when nothing was dragged into the list in the Inspector, when a search or filter matched nothing, or when the code runs before the list is filled.list[list.Count - 1]on an empty list asks for index -1. - An off-by-one loop or “last item” read.
for (int i = 0; i <= list.Count; i++)runs one step too far.list[list.Count]is one past the last item. - Capacity mistaken for size.
new List<int>(10)reserves memory for ten items and has aCountof 0.scores[3] = 500throws. - The index is -1.
IndexOfandFindIndexreturn -1 when nothing matches. In C# the%operator keeps the sign, so(index - 1) % Countis -1 whenindexis 0. - Items are removed inside a forward loop. A loop that stored
Countin a variable before it started keeps going after the list has shrunk. - A stale index.
selectedSlotwas 4, the player sold an item, and the list now has four entries. The same thing happens across sessions: a character index stored inPlayerPrefsor a save file outlives an update that removed a character. - Two lists assumed to be the same length.
icons[i]inside a loop overnamesthrows on the first index thaticonsdoes not have. - A random index with the wrong range.
Random.Range(0, list.Count + 1)can returnCount. So can(int)Random.Range(0f, list.Count), because the float overload includes its maximum. - An index that comes from outside the list. A UI Dropdown value read after its options changed, a level number from a URL or a save, a slot number in a network message.
How to find the line and the cause
Read the stack trace from the top and stop at the first frame whose path starts with Assets/. In the example that is WaypointPatrol.cs:31. Double-click the Console entry to open that line. If the line indexes more than one list, split it into separate statements and run again, so the line number points at one of them.
Then log the two numbers the exception left out, just before the failing line:
Debug.Log($"index={index} count={waypoints.Count}", this);
Passing this as the second argument makes the Console entry clickable, and Unity highlights the object in the Hierarchy. That matters when one instance out of fifty has an empty list.
| What the log shows | Cause |
|---|---|
count=0 | Empty list (causes 1 and 3). Click the entry and check that object’s Inspector. |
index equals count | Off by one, a removal during the loop, or a random range that is one too wide (causes 2, 5, 8) |
index=-1 | A failed search or a negative modulo (cause 4) |
index is well past count | A stale or external index, or two lists of different lengths (causes 6, 7, 9) |
If no frame in the trace points into Assets/ and every frame begins with UnityEditor, the exception comes from an editor window and not from your game. Restarting the editor usually clears it. If the frames belong to a package, look for code of yours that changes a list while the package is iterating it.
In a player build the trace has line numbers only if the build keeps them. A Development Build normally does. For IL2CPP release builds, set IL2CPP Stacktrace Information in the Player settings to Method Name, File Name, and Line Number. Without line numbers you still get the method name, which is usually enough to find the indexer. Reading Game Stack Traces: A Beginner’s Guide for Game Developers covers the format in more detail.
Fix 1: check Count before you index
// Broken: throws when spawnPoints is empty
Transform spawn = spawnPoints[0];
// Fixed
if (spawnPoints.Count == 0)
{
Debug.LogError("Spawner: spawnPoints is empty, nothing to spawn at", this);
return;
}
Transform spawn = spawnPoints[0];
The log line is part of the fix. An empty list that should have had entries is a setup mistake, and a silent return turns it into “enemies sometimes do not spawn”. For the capacity mistake, add the elements or use an array, which does start with its full length:
// Broken: capacity 10, Count 0
List<int> scores = new List<int>(10);
scores[3] = 500;
// Fixed: an array has ten slots from the start
int[] scores = new int[10];
scores[3] = 500;
Fix 2: correct the loop, and remove items backward
// Broken: <= runs one step past the end
for (int i = 0; i <= enemies.Count; i++)
enemies[i].Tick();
// Fixed
for (int i = 0; i < enemies.Count; i++)
enemies[i].Tick();
Removing inside a forward loop fails in two ways. With a cached count it throws:
// Broken: count is wrong after the first removal
int count = enemies.Count;
for (int i = 0; i < count; i++)
{
if (enemies[i].IsDead)
enemies.RemoveAt(i);
}
With i < enemies.Count in the condition it does not throw, but it skips the item that slides into the removed slot, so one of two dead enemies standing next to each other in the list survives. Loop backward, or let the list do the work:
// Fixed: removals only shift items that were already visited
for (int i = enemies.Count - 1; i >= 0; i--)
{
if (enemies[i].IsDead)
enemies.RemoveAt(i);
}
// Or
enemies.RemoveAll(e => e.IsDead);
Removing inside a foreach throws a different exception. That one is covered in How to Fix “InvalidOperationException: Collection was modified; enumeration operation may not execute” in Unity. When you walk two lists together, loop to the shorter one with Mathf.Min(names.Count, icons.Count) and log an error if the lengths differ.
Fix 3: make computed indexes land inside the list
Wrapping around
// Broken: at index 0 this gives -1
currentWeapon = (currentWeapon - 1) % weapons.Count;
// Fixed: add Count before taking the remainder
currentWeapon = (currentWeapon - 1 + weapons.Count) % weapons.Count;
Both lines divide by Count, so check that the list is not empty first. A remainder by zero throws DivideByZeroException.
Search results
int index = inventory.IndexOf(item);
if (index < 0)
{
Debug.LogWarning($"Inventory: {item.name} is not in the list", this);
return;
}
inventory.RemoveAt(index);
If all you need is the removal, inventory.Remove(item) returns false for a missing item and never throws.
Random picks
// Broken: can return clips.Count
AudioClip clip = clips[Random.Range(0, clips.Count + 1)];
// Broken: the float overload includes the maximum
AudioClip clip = clips[(int)Random.Range(0f, clips.Count)];
// Fixed: the int overload excludes the maximum
if (clips.Count > 0)
{
AudioClip clip = clips[Random.Range(0, clips.Count)];
audioSource.PlayOneShot(clip);
}
Random.Range(int, int) returns values from the minimum up to, but not including, the maximum, so Random.Range(0, clips.Count) is exactly the valid index range. The Count > 0 check is still needed: when both arguments are equal the method returns the minimum, so on an empty list it returns 0 and the indexer throws. Writing clips.Count - 1 as the maximum does not throw. It never picks the last clip.
Fix 4: validate indexes that arrive from somewhere else
An index that was valid when it was stored is a guess by the time it is used. Re-check it after every change to the list, and when it is loaded:
// After removing an item from the list
selectedSlot = Mathf.Clamp(selectedSlot, 0, Mathf.Max(0, slots.Count - 1));
// When loading a stored index
int saved = PlayerPrefs.GetInt("selectedCharacter", 0);
if (saved < 0 || saved >= characters.Count)
{
Debug.LogWarning($"Saved character index {saved} is invalid, {characters.Count} characters exist. Using 0.");
saved = 0;
}
After the clamp, selectedSlot is 0 for an empty list, so the read still needs a Count check. For anything that reaches disk, store a stable id ("knight") in place of a position (2). Positions change when you reorder or delete entries in an update. Ids do not.
A guard helper
using System.Collections.Generic;
public static class ListExtensions
{
public static bool TryGet<T>(this IReadOnlyList<T> list, int index, out T value)
{
if (list != null && index >= 0 && index < list.Count)
{
value = list[index];
return true;
}
value = default;
return false;
}
}
List<T> and arrays both implement IReadOnlyList<T>, so one method covers both:
if (!levels.TryGet(levelIndex, out LevelData level))
{
Debug.LogError($"LevelLoader: no level at index {levelIndex}, {levels.Count} levels exist", this);
return;
}
Use it where the index comes from data you do not control. Inside a plain for loop over the same list it only adds noise, and a wrong index there is a bug you want to see.
How to confirm the fix
Run the cases the happy path skips. Empty the list in the Inspector and enter Play mode. Test with one element, where “first” and “last” are the same item. Step the selection past both ends. Kill two adjacent enemies in the same frame. Load a save or PlayerPrefs value written by a version that had more entries. The pass condition is no ArgumentOutOfRangeException in the Console or in Player.log, and a log line that names the index and the count for each bad value you planted.
What a report from a player’s machine tells you
The Bugnet Unity SDK files unhandled exceptions and Debug.LogError calls through Application.logMessageReceived, with the stack trace, recent log lines, game version, platform and OS. For this exception the stack trace carries the information, because the message is identical for every list in the game. That has two consequences. Reports with the same title stack into one entry, so index errors from two unrelated scripts can share an entry until you open them and compare traces. And the SDK files each distinct message once per session, so a second index bug in the same session is not filed again.
The guards above solve both. An error such as “LevelLoader: no level at index 7, 5 levels exist” has its own title, its own entry and its own occurrence count, and it contains the two numbers the runtime never records. Bugnet cannot recover the index or the list size from the exception alone. What a filed report contains is described in the bug reports guide.
Related guides
- What Does “Index was outside the bounds of the array” Mean? (and How to Fix It)
- How to Fix “InvalidOperationException: Collection was modified; enumeration operation may not execute” in Unity
- How to Fix “ArgumentNullException: Value cannot be null” in Unity
- How to Fix “KeyNotFoundException: The given key was not present in the dictionary” in Unity
- 12 Common Unity Errors and How to Fix Them
Frequently asked questions
What does “Index was out of range. Must be non-negative and less than the size of the collection” mean in Unity?
Code used a List index that is below 0 or not below the list’s Count. The valid indexes are 0 to Count minus 1. It is a standard .NET exception thrown by List and similar collections, and the first stack frame inside Assets is the line that used the bad index.
What is the difference between ArgumentOutOfRangeException and IndexOutOfRangeException?
They report the same mistake from different types. A List throws ArgumentOutOfRangeException with the text Index was out of range, and an array throws IndexOutOfRangeException with the text Index was outside the bounds of the array. The causes and the fixes are the same.
Why do I get this error when the list has items in the Inspector?
The object that threw is probably not the one you are looking at. Another instance or prefab variant can have an empty list, or the code runs before the list is filled at runtime. Pass this as the second argument to Debug.Log so that clicking the Console entry highlights the object that failed.
Is Random.Range(0, list.Count) safe for picking a random list element?
Yes, as long as the list is not empty. The integer overload excludes the maximum, so it returns 0 to Count minus 1. On an empty list it returns 0 and the indexer throws, and the float overload includes its maximum, so casting its result to int can produce Count.
How do I remove items from a List inside a loop without this error?
Loop backward from Count minus 1 down to 0 and call RemoveAt, or call RemoveAll with a condition. A forward loop with a cached count runs past the end after the first removal, and a forward loop without one skips the item after each removed entry.
The exception never says which list or which index. Log the index and the Count at the failing line, and the cause is usually obvious from those two numbers.