# Unity 2D: Can’t resolve ArgumentOutOfRangeException: Index was out of range

I am very much a novice to coding with no background on this at all so the code you see here may be terrible.

Basically I’m making an endless runner, made up of a player character and a set of obstacle prefabs. The obstacle prefabs have a trigger on them so that when the player hits it, it spawns the next prefab. I’m using the code below, and when the player hits the first spawn trigger it will spawn a prefab, but on tripping the next trigger it gives me the ArgumentOutOfRangeException error in the console and doesn’t spawn anything.

public class ObsTrigger : MonoBehaviour {

 public GameObject spawnTrigger;
[SerializeField] private List<Transform> obstacleList;

private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
for (int i = 0; i < obstacleList.Count; i++)
{
spawnObstacle();
}
}
}

public void spawnObstacle()
{
{
Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
Instantiate(chosenLevelPart);
}
}


}

If anyone can point me in the right direction I would really appreciate it!

• just write obstacleList.Count-1 as arrays and list start from 0 to count-1 Dec 1 '19 at 8:05
• There is nowhere in this code that Count - 1 would be an effective fix, @virtouso. The for loop is already testing < Count, and the integer version of Random.Range selects values between min and max - 1 already. Dec 1 '19 at 15:26

In the following chunk of code, you should check if there are any elements in your obstacle list before you try to access them

public void spawnObstacle()
{
Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
Instantiate(chosenLevelPart);
}


should be

public void spawnObstacle()
{
if (obstalceList.Count > 0)
{
Transform chosenLevelPart = obstacleList[Random.Range(0, obstacleList.Count -1)];
Instantiate(chosenLevelPart);
}
}


because if there are no objects in the list, obstacleList[0] will still attempt to access the first element of the list, which would then be out of range.

• That makes sense, I’ve amended the code to what you suggested and the error message doesn’t pop up any more, but it still doesn’t spawn another prefab after collision. Dec 2 '19 at 12:37