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?