How do I create a multidimensional array of objects in c#

FreakinaBox picture FreakinaBox · Aug 10, 2012 · Viewed 13.5k times · Source

I am trying to make a script that dynamically generates world chunks by making a height map then filling out the terrain blocks from there. My problem is creating a 2 dimensional array of objects.

public class Chunk
{
    public Block[,] blocks;

    Generate(){
        //code that makes a height map as a 2 dimensional array as hightmap[x,y]=z
        //convert heightmap to blocks
        for (int hmX = 0; hmX < size; hmX++)
        {
            for (int hmY = 0; hmY < size; hmY++)
            {
                blocks[hmX, hmY] = new Block(hmX, hmY, heightmap.Heights[hmX, hmY], 1);
            }
        }
    }
}

this is giving me the error:

NullReferenceException was unhandled, Object reference not set to an instance of an object.

Answer

Nathan Andrew Mullenax picture Nathan Andrew Mullenax · Aug 10, 2012

You just need to add new before the loop:

Block[,] blocks = new Block[size,size];

Or rather, within the generate function (all else the same):

blocks = new Block[size,size];

Otherwise you'll be shadowing the original 'blocks' variable.