Declaring and Initializing 2D arrays in C#

Can anyone tell me what's the best way to initialize a 2D array of vectors in C#??

This is what I tried to do:

private Vector3[][] spawnGrid;


spawnGrid[0][0] = new Vector3(-2.5f, 0f, 1.5f);
        spawnGrid[0][1] = new Vector3(-2.5f, 0f, 0.5f);
        spawnGrid[0][2] = new Vector3(-2.5f, 0f, -1.5f);
        spawnGrid[0][3] = new Vector3(-2.5f, 0f, -2.5f);

        spawnGrid[1][0] = new Vector3(-1.5f, 0f, 1.5f);
        spawnGrid[1][1] = new Vector3(-1.5f, 0f, 0.5f);
        spawnGrid[1][2] = new Vector3(-1.5f, 0f, -1.5f);
        spawnGrid[1][3] = new Vector3(-1.5f, 0f, -2.5f);

        spawnGrid[2][0] = new Vector3(0.5f, 0f, 1.5f);
        spawnGrid[2][1] = new Vector3(0.5f, 0f, 0.5f);
        spawnGrid[2][2] = new Vector3(0.5f, 0f, -1.5f);
        spawnGrid[2][3] = new Vector3(0.5f, 0f, -2.5f);

I dont get any syntax error but I get a NullReferenceException at the point where I access an element of this array like so:

GameObject GO;
            GO = (GameObject)Instantiate(enemies[0], spawnGrid[0][0], transform.rotation);

Does anyone see the problem here?

Please help!

You haven't initialized any of the arrays. In any case, that's the syntax for a jagged array; seems like you want a 2D array.

private Vector3[,] spawnGrid = new Vector3[3, 4];

--Eric

2 Likes

Thanks for replying. But this time, I am getting a new error like such:

error CS0022: Wrong number of indexes `1' inside [], expected `2' at the point I am accessing an element.

Do you see the problem here?

Thanks!


If you intialize the array as eric proposed, you need to access elements like this:

spawnGrid[0,0] = new Vector3(-2.5f, 0f, 1.5f);

Thanks a lot guys...I am not familiar with a lot of syntax in C# and I am still very new to this language. But thanks to you guys to make my life easier!

You are probably done with this coding already, but you can make it even simpler just by doing this:

  • private Vector3[,] spawnGrid = new Vector3[3, 4];
    • void SpawnGrid()
  • {
  • for (int i = 0; i < 3; i++)
  • {
  • for (int j = 0; j < 4; j++)
  • {
  • spawnGrid[i, j] = new Vector3(x, 0f, z);
  • z -= 1;
  • }
    • x += 1;
  • z = 1.5f; //gives original value back to Z.
  • }
  • }