Weird vertices appear when generating grid full of quads
I am trying to generate a grid full of quads that are made up of triangles. Everything works fine at first but when I increase width and height to 300 or more it starts generating weird triangles that aren't supposed to be there. I have no idea what might cause this issue. My guesses are I am drawing triangles wrong.
This is 100x100 grid and it works just fine
This is 300x300 grid which does some weird stuff
From underneath it generates this weird looking spaghetti shapes. I tried changing triangles order but it doesn't help. It only gets wilder. One last thing I should probably mention is those weird triangles are rows that should be generated in their own coordinates, the issue is again in my opinion is triangles array. I will stop talking now and put my code here.
Code is a little bit too long but I hope you will take a look at it:
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class MeshGeneration : MonoBehaviour
{
Vector3[] vertices;
int[] triangles;
public int width, height;
[Range(0f, 1f)]
public float resolution;
Mesh mesh;
private void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
GenerateMesh();
UpdateMesh();
}
void GenerateMesh()
{
vertices = new Vector3[(width + 1) * (height + 1)];
for (int x = 0, i = 0; x < width+1; x++)
{
for (int z = 0; z < height+1; z++)
{
vertices[i] = new Vector3(x * resolution, 0, z * resolution);
i++;
}
}
triangles = new int[width * height * 6];
int quad = 0;
int vertice = 0;
for (int x = 0; x < height; x++)
{
for (int z = 0; z < width; z++)
{
triangles[quad + 0] = vertice + 0;
triangles[quad + 1] = vertice + 1;
triangles[quad + 2] = vertice + width + 2;
triangles[quad + 3] = vertice + width + 2;
triangles[quad + 4] = vertice + width + 1;
triangles[quad + 5] = vertice + 0;
vertice++;
quad += 6;
}
vertice++;
}
}
public void UpdateMesh()
{
mesh.name = "ShittyTerrain";
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
}
I hope I made everything clear for you. If you have ever encountered an issue like this I would greatly appreciate even a small hint. Thank you if you have read so far!