2D数组已初始化,但所有项都为null C#

时间:2016-03-15 07:52:07

标签: c# arrays unity3d unity5

所以在Unity中我的this.tilesX和this.tilesY都是具有值的公共变量。它们设置在Unity的检查员中。数组初始化后的debug.log读出“10 x tiles 10 y tiles”。所以我知道这两个变量都已初始化。

但是,当我去检查this.tileLayer1 2D数组的元素是否为null时,它返回debug.log打印出“tile is null”。我完全迷失了。下面是初始化数组的函数以及我的自定义Tile类的构造函数。

void Start () {

    this.tileLayer1 = new Tile[this.tilesY, this.tilesX];

    Debug.Log(tilesX + " x tiles " + tilesY + " y tiles");

    for (int y = 0; y < this.tileLayer1.GetLength(0); y++)
    {
        for (int x = 0; x < this.tileLayer1.GetLength(1); x++)
        {
            if (this.tileLayer1[x, y] == null)
            {
                Debug.Log("tile is null");
            }
        }
    }

    this.BuildMesh();
}

这是新Tile代码调用的构造函数。

public Tile () {
    this.totalVerts = this.vertX * this.vertY;

    this.vertices = new Vector3[totalVerts];
    this.normals = new Vector3[totalVerts];
    this.uv = new Vector2[totalVerts];

    this.triangles = new int[6];
}

我不认为构造函数与它有很大关系,但谁知道。

3 个答案:

答案 0 :(得分:6)

这是因为null仅使用for (int y = 0; y < this.tileLayer1.GetLength(0); y++) { for (int x = 0; x < this.tileLayer1.GetLength(1); x++) { this.tileLayer1[x, y] = new Title(); } } 值初始化数组。

您需要初始化每个值

icon.imageset

答案 1 :(得分:2)

您必须初始化数组中的每个元素:

tileLayer1[0,0] = new Tile();

答案 2 :(得分:1)

除非数组元素类型是值类型,否则初始化后项目将始终为null,并且必须逐个初始化元素。

如果这不是预期的行为,将Tile作为值处理是有意义的,那么将其转换为值类型(struct),这样数组将由{{1}初始化}(按位零)元素。这意味着default(Tile)vertices等在每个元素中都是空引用,因为在数组初始化时没有为元素执行构造函数。