5

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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
If you don't know either dimension, maybe you could use generic container classes. You could do something like Dictionary<Point,Chunk> chunks = new Dictionary<Point,Chunk>(); where point contains chunk coordinates. Alternatively, if it's always a rectangle, List<List<Chunk>> chunks = new List<List<Chunk>>();.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.