4

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.

FreakinaBox
  • 421
  • 1
  • 4
  • 15

1 Answers1

6

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.

  • That fixes it there, but I do the same thing with the chunks being stored in an multidimensional array of chunks. The only problem is I don't know how many chunks their will be. Should I switch to a jagged array instead of a multidimensional for the chunks, or is their a way to make this work with a dynamic size? – FreakinaBox Aug 10 '12 at 18:23
  • If you don't know either dimension, maybe you could use generic container classes. You could do something like `Dictionary chunks = new Dictionary();` where point contains chunk coordinates. Alternatively, if it's always a rectangle, `List> chunks = new List>();`. – Nathan Andrew Mullenax Aug 10 '12 at 18:35