Outside of bounds error

I copied some numbers from a brackeys tutorial (too lazy to calculate them myself :wink: ) but I get a outside of bounds error at line 21. I dont understand why it should be declared correctly.

public void GenerateChunkMesh(int widthInUnits, float[,] noise)
    {
        verts = new Vector3[(widthInUnits + 1) * (widthInUnits + 1)];
        tris = new int[widthInUnits * widthInUnits * 6];

        for(int y = 0, i = 0; y < widthInUnits; y++)
        {
            for(int x = 0; x < widthInUnits; x++)
            {
                verts[i] = new Vector3(transform.position.x + x, noise[x, y], transform.position.y + y);
                i++;
            }
        }

        int vert = 0;
        int triangles = 0;
        for (int j = 0; j < verts.Length - 1; j++)
        {
            for (int i = 0; i < verts.Length - 1; i++)
            {
                tris[triangles + 0] = vert + 0;
                tris[triangles + 1] = vert + widthInUnits + 2;
                tris[triangles + 2] = vert + 1;
                tris[triangles + 3] = vert + 1;
                tris[triangles + 4] = vert + widthInUnits + 1;
                tris[triangles + 5] = vert + widthInUnits + 2;

                triangles += 6;
                vert++;
            }
            vert++;
        }
    }

Surely I am overseeing something obvious here but I dont get it.

Line 17 and line 19 termination comparison quantities are incorrect.

Line 3 makes the verts array out of the square of (widthInUnits+1)

Line 4 makes the tris array out of a comparably-squared quantity, expanded by 6 for 2 tris per quad.

So a 9x9 width would be 100 verts, and 81 * 6 tris.

Then you are iterating 99 verts within another loop iterating 99 verts, so thatโ€™s why you are spilling beyond the tris array.

Most likely you want lines 17 and 19 to both continue when the index value is below widthInUnits

for (int j = 0; j < widthInUnits; j++)