Help! Array index is out of range (C#)
Hi there, newbie's here. I have a very simple code, but just can't figure out what went wrong. The console says that line 12 went wrong, and warns me of the error 'IndexOutOfRangeException: Array index is out of range.'
using UnityEngine;
using System.Collections;
public class Rand2 : MonoBehaviour
{
void Start()
{
int[] test1 = new int[] { 1, 2, 3, 4, 5 };
string test1TXT = "";
foreach (int i in test1)
{
test1TXT += test1[i].ToString() + " ";
}
Debug.Log(test1TXT);
}
}
array indices are zero-based... it might be worth spending a little time on some c# tutorials.
not that it's relevant to your example (with only 5 elements), but string concatenation generates a lot of garbage.
Answer by MerryAce123 · Oct 20, 2015 at 07:53 PM
You are not using the foreach loop correctly. Int i represents the number that's in your array not the index. So you can either change the foreach loop to a simple for loop this way: for (int i = 0; i < test1.Length; i++)
or you can keep the foreach loop and change the code inside it this way: test1TXT += i.ToString() + " ";
Your answer
![](https://koobas.hobune.stream/wayback/20220612042048im_/https://answers.unity.com/themes/thub/images/avi.jpg)