- Home /
Convert 1D array to 2D array
I am tring to convert a 1D array to a 2D array for better organization, but it won't work. it says the array index is out of range on line 15 of this script:
class BlockData {
var heightMap : int[,];
var floorMap : int[,];
var wallsMap : int[,];
var spawnMap : int[,];
function BlockData(size : int, height : int[], floor : int[], walls : int[], spawn : int[]){
heightMap = new int[size,size];
floorMap = new int[size,size];
wallsMap = new int[size,size];
spawnMap = new int[size,size];
var i : int = 0;
for (var x: int = 0; x < height.Length; x++){
for (var y: int = 0; y < height.Length; y++){
Debug.Log(height.Length+" "+i);
heightMap[x,y] = height[i]; //THIS LINE OVER HERE --- The rest of the code is not even being processed, and it's just copies of this loop chain.
i++;
}
}
i = 0;
for (x = 0; x < floor.length; x++){
for (y = 0; y < floor.length; y++){
floorMap[x,y] = floor[i];
i++;
}
}
i = 0;
for (x = 0; x < walls.length; x++){
for (y = 0; y < walls.length; y++){
wallsMap[x,y] = walls[i];
i++;
}
}i = 0;
for (x = 0; x < spawn.length; x++){
for (y = 0; y <= spawn.length; y++){
spawnMap[x,y] = spawn[i];
i++;
}
}
}
}
You might have to loop through and initialize each array:
for ( var i : int = 0; i < size; i ++ ) {
height$$anonymous$$ap[i] = new int [size];
}
I'm not sure... I've never used 2D arrays in Unity, but it's worth a shot.
@jahroy: no, the arrays are already being initialized properly.
Answer by aldonaletto · Jan 21, 2012 at 12:59 AM
You're doing the x and y loops height.Length times each, what results in height.Length height.Length* iterations. Since you're incrementing i each iteration, height[i] will go out of range after the first y loop.
If I understood correctly what you're trying to do, your loops should count from 0 to size, not 0 to height.Length, and size should be >= the square root of height.Length:
... var i : int = 0; for (var x: int = 0; x < size; x++){ for (var y: int = 0; y < size; y++){ Debug.Log(height.Length+" "+i); heightMap[x,y] = height[i]; i++; } } ...As you said, the other loops are copies of this one, thus they all have the same problem.
Tactical Facepalm. EDIT: Still doesn't work, it gives the same error. I'm trying to create a 2D arraw with its boundaries at [size,size]
, to create a square grid.
Answer by Eric5h5 · Jan 21, 2012 at 12:58 AM
Both the inner and out loops are repeating height.Length
times, so the total number of values is height.Length * height.Length
, which is clearly way out of range since the total in the array is height.Length
only.
Your answer
Follow this Question
Related Questions
2D array problem in C# 2 Answers
Matching Index of two Arrays after one Array is sort 3 Answers
IndexOutOfRangeException: Array index is out of range 2 Answers
Array error - Index is less than 0... 3 Answers
array problem 1 Answer