如何在c#中创建对象的多维数组, [英] How do I create a multidimensional array of objects in c#

查看:889
本文介绍了如何在c#中创建对象的多维数组,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个脚本动态生成世界块,通过制作一个高度地图,然后从那里填充地形块。我的问题是创建一个二维的对象数组。

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);
            }
        }
    }
}

是给我错误:


NullReferenceException未处理,对象引用未设置为对象的
实例。

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


推荐答案

你只需要在循环之前添加新的:

You just need to add new before the loop:

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

或者说,在generate函数内(所有其他都相同):

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

blocks = new Block[size,size];

否则,将会隐藏原始的「blocks」变数。

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

这篇关于如何在c#中创建对象的多维数组,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆