IndexOutOfRange while creating mesh

I tried following a tutorial by Sebastian Lague (YouTube link: Procedural Landmass Generation (E06: LOD) - YouTube ). I had to modify his code slightly. Here’s a code snippet:

using UnityEngine;

public class MeshGeneration : MonoBehaviour
{
    public int width;

    public GameObject plane;
    int triangleIndex;

    void Start()
    {
        GenerateMesh();
    }

    public void GenerateMesh()
    {
        Vector3[] vertices = new Vector3[width*width];
        int[] triangles = new int[(width - 1) * (width - 1) * 6];
        Vector2[] uvs = new Vector2[width * width];

        int vertexIndex=0;
        float topLeftX = (width - 1) / -2f;
        float topLeftZ = (width - 1) / 2f;

        for (int y = 0; y < width; y++)
            for (int x = 0; x < width; x++)
            {
                vertices[vertexIndex] = new Vector3(topLeftX + x, 0, topLeftZ - y);
                uvs[vertexIndex] = new Vector2(x / (float)width, y / (float)width);
                if (x < width - 1 && y < width - 1)
                {
                    AddTriangle(triangles, vertexIndex, vertexIndex + width + 1, vertexIndex + width);
                    AddTriangle(triangles, vertexIndex + width + 1, vertexIndex, vertexIndex + 1);
                }
                vertexIndex++;
            }

        Mesh mesh = new Mesh();

        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        mesh.RecalculateNormals();

        plane.GetComponent<MeshFilter>().mesh = mesh;
    }

    void AddTriangle(int[] tri,int a,int b,int c)
    {
        tri[triangleIndex] = a;
        tri[triangleIndex + 1] = b;
        tri[triangleIndex + 2] = c;
        triangleIndex += 3;
    }
}

It seems that the code should run but I get IndexOutOfRangeException on line 50 (AddTriangle() method). I’m using width = 500. Has anyone ran into the same issue while following this tutorial?

I don’t see a direct issue with index out of bounds. However you might want to make sure you set “triangleIndex” to 0 at the beginning of “GenerateMesh”. Note that this line:

uvs[vertexIndex] = new Vector2(x / (float)width, y / (float)width);

should be

uvs[vertexIndex] = new Vector2(x / (float)(width-1), y / (float)(width-1));

If you want to map the texture to the whole plane. Since the uv goes from 0 to 1 you want to use that whole range. However your x and y values only go up to “width-1”. So to get 1 at the highest x / y position you have to divide by “width-1”