Array index is out of range. c#
Hey, Guys. I gonna implement isometric lvl generation, but theres traceback (IndexOutOfRangeException: Array index is out of range.) occurs after first row being generate. Any suggestions, please 7
public class levelgenerat : MonoBehaviour
{
const float SizeW = 1.28f;
const float SizeH = 0.5f;
public GameObject ground1;
public GameObject ground2;
public int[,] numbers = {
{1,0,0,0},
{1,0,1,0},
{0,0,1,1},
{1,1,0,0}
};
// Use this for initialization
void Start()
{
for (int i = 0; i < numbers.Length; i++)
{
for (int j = 0; j < numbers.Length; j++)
{
Vector2 pos = new Vector2(j * SizeW / 2 + i * SizeW / 2, j * SizeH / 2 + i * SizeH / 2);
if (numbers[i, j] == 1)
{
GameObject ground = Instantiate(ground1, pos, Quaternion.identity) as GameObject;
}
else if (numbers[i, j] == 0)
{
GameObject ground = Instantiate(ground2, pos, Quaternion.identity) as GameObject;
}
}
}
}
Answer by LiloE · Mar 06, 2017 at 02:41 PM
Multi dimensional arrays work a bit differently
Replace your loop code with this:
//....
for (int i = 0; i < numbers.GetLength(0); i++)
{
for (int j = 0; j < numbers.GetLength(1); j++)
//...
The Length
property returns 16, which is the combined length of all dimensions.
Since you have 2 dimensions (rows and columns) you need to use the method GetLength
instead.
Answer by hanguksaram · Mar 06, 2017 at 03:21 PM
Thank you!!! @LiloE
@hanguksaram - please mark answer as accepted if it helped (little green checkmark) . Thanks :-)
If i wanna change my second loop's statement on (int j = numbers.GetLength(1); j >= 0; j--) it also shows traceback, What should i do in this case ?)
Your answer
Follow this Question
Related Questions
Why arrays don't set on void Start() ? 1 Answer
Destroy question if its already asked 1 Answer
Object not at 0 1 Answer
Cant define array from other script 0 Answers