ArgumentOutOfRangeException: Argument is out of range. -> Index


for some reasons I can’t get the index ArgumentOutOfRangeException solved. I tried variations of the condition (< oder <=) and the post/pre increment and other stuff. Tee strange thing is; this functions worked until I packed them together in one Method, but I see no problem as they’re individually calculated in their swich cases.

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[UnityEngine.Vector3].get_Item (Int32 index) (at /Users/builduser>/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
Squad.buildFormation (FormationType type) (at Assets/WorldObject/Unit/Squad.cs:39)
Squad.Update () (at Assets/WorldObject/Unit/Squad.cs:22)

Here’s the code:

   public void buildFormation(FormationType type)
        List<Vector3> pts = getFormationPoints(type, null);
        Transform pivot = squadMembers[pivot_id].transform;
        Quaternion look_rot = pivot.rotation;
            for (int i = 0; i <= squadMembers.Count; ++i)
                squadMembers_.transform.position = pts*;*_

squadMembers*.transform.rotation = look_rot;
get FormationPoints:_

public List getFormationPoints(FormationType type, Transform destination)
List pts = new List();
Transform pivot;
Vector3 offset;

switch (type)
case FormationType.Line:
pivot_id = squadMembers.Count / 2;
if (destination != null)
pivot = destination;
pivot = squadMembers[pivot_id].transform;

offset = pivot.position;
offset = offset.normalized * distance;

for (int i = 0; i <= squadMembers.Count; ++i)
pts = pivot.position + offset * (i - pivot_id);

case FormationType.None:
// smth
return pts;

The problem occurs at both foreach block but if I debug the lenght of the arrays it returns an Integer.

if (squadMembers.Count == pts.Count)
wrapped arount the loops would return fals, which is strange.
The squad members are public lists for the class:
public List squadMembers = new List();

  1. Change <= to < in both of your for loops. You do this in the first one because the last valid index in an array is equal to its Count-1, so you want to stop the loop before you it tries to use the Count as an index. You do this in the second one because pts has to be the same size as squadMembers in your setup.
  2. Either make pts an array of Vector3s instead of a list, or use pts.Add(item) if you need it to be a list. I suggest the former.

You can’t access list members without adding them first.

Try this:

Change getFormationPoints to start like this

 public Vector3[] getFormationPoints(FormationType type, Transform destination)
    var pts = new Vector3[squadMembers.Count];

And in buildFormation

Vector3[] pts = getFormationPoints(type, null);