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*; //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 = 0;_
_
for (x = 0; x < walls.length; x++){_
_
for (y = 0; y < walls.length; y++){_
_ wallsMap[x,y] = walls;
i++;
}*_

* }i = 0;*
* for (x = 0; x < spawn.length; x++){*
* for (y = 0; y <= spawn.length; y++){*
_ spawnMap[x,y] = spawn*;
i++;
}
}
}
}*_

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.

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_ 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++;
}
}


As you said, the other loops are copies of this one, thus they all have the same problem.