问题
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:
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.
来源:https://stackoverflow.com/questions/11907069/how-do-i-create-a-multidimensional-array-of-objects-in-c-sharp