Basic terrain generator

I am trying to generate a array of blocks. This is my code:


class MapGenerator extends MonoBehaviour {
function Start(){
	gameMatrix = MakeVoxels(128, 128, 128);
function MakeVoxels(sizeX:int, sizeY:int, sizeZ:int){
	var matrix : Block[];
	var currX:int;
	var currY:int;
	var currZ:int;
	for (currZ = 0-(currZ/2); currZ<=sizeZ; currZ++){
		for (currY = 0-(currY/2); currY<=sizeY; currY++){
			for (currX = 0-(currX/2); currX<=sizeX; currX++){
				matrix[(currZ*sizeZ)+(currY*sizeY)+currX] = new Block(BlockMaterial.AIR,currX, currY, currZ);
	return matrix;



class Block{

var breakTime:float;

var color:Color;

public var blockMat:Material;

function Block(mat:BlockMaterial, x:int, y:int, z:int){

	var cube:GameObject;

	if (mat == BlockMaterial.AIR){

		cube = SetBlockProps(x, y, z, new Color(255,255,255,1), false);

	}else if (mat == BlockMaterial.DIRT){

		cube = SetBlockProps(x, y, z, new Color(84,59,20,255), true);

	}else if (mat == BlockMaterial.STONE){

		cube = SetBlockProps(x, y, z, new Color(111,111,111,255), true);



function SetBlockProps(x:int, y:int, z:int, col:Color, solid:boolean){

	var c:GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);

	c.transform.position = new Vector3(x,y,z);

	c.renderer.material = blockMat;

	c.renderer.material.color = col;

	c.collider.enabled = solid;

	return c;




enum BlockMaterial{





I want to generate a matrix of cubes on MapGenerator.js, but it errors on line

matrix[(currZ*sizeZ)+(currY*sizeY)+currX] = new Block(BlockMaterial.AIR,currX, currY, currZ);

This is the error:
NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)
MapGenerator.MakeVoxels (Int32 sizeX, Int32 sizeY, Int32 sizeZ) (at Assets/Scripts/MapGenerator.js:14)
MapGenerator.Start () (at Assets/Scripts/MapGenerator.js:4)

The problem is that while you declare matrix in your script, you never tell it how long it’s supposed to be! You should initialise matrix with the total length it is expected do end up, something like this-

var matrix : Block[] = new Block[sizeX * sizeY * sizeZ];

Another thing, you never actually define a return type for that function? I’m not quite sure about the syntax, but isn’t that a problem? Or is it another one of those things where JavaScript’s weird fuzzy syntax magically makes it work for you?