Joshua Blevins
Joshua Blevins

Reputation: 697

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

So in Unity my this.tilesX and this.tilesY are both public variables that have a value in them. They are set in Unity's inspector. The debug.log after the initialization of the array reads out "10 x tiles 10 y tiles". So I know that both of those variables are initialized.

However, when I go to check if the this.tileLayer1 2D array's elements are null it returns the debug.log prints out "tile is null". I am completely lost. Below is the function that initializes the array as well as the constructor for my custom 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();
}

Here is the constructor that the new Tile code calls.

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

I do not think that the constructor has much to do with it, but who knows.

Upvotes: 0

Views: 3067

Answers (3)

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18013

Unless the array element type is a value type, the items will be always null after initialization and you must initialize the elements one by one.

If this is not the expected behavior and it makes sense to handle Tile as a value, then turn it into a value type (struct) so the array will be initialized by default(Tile) (bitwise zero) elements. That means vertices, normals, etc. will be null references in each element because no constructor is executed for the elements on array initialization.

Upvotes: 2

Dovydas Šopa
Dovydas Šopa

Reputation: 2300

That's because this.tileLayer1 = new Tile[this.tilesY, this.tilesX]; only initialize array with null values.

You need to initialize each value

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

Upvotes: 6

Paweł Marecki
Paweł Marecki

Reputation: 630

You have to initialize each element in array:

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

Upvotes: 2

Related Questions