二维数组已初始化,但所有项均为空 C#

2D array is initialized, but all items are null C#

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

但是,当我检查 this.tileLayer1 二维数组的元素是否为空时,returns debug.log 打印出 "tile is null"。我完全迷路了。下面是初始化数组的函数以及我的自定义 Tile class.

的构造函数
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];
}

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

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

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

那是因为 this.tileLayer1 = new Tile[this.tilesY, this.tilesX]; 只用 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();
    }
}

除非数组元素类型为值类型,否则初始化后项将始终为空,您必须逐一初始化元素。

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