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

徘徊边缘 提交于 2019-12-23 15:57:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!