- Home /
How to generate a subdivided plane mesh
Hello. I am trying to make a mesh that displays a grid of 16x16 vertices. I have already been successful at plotting the 256 vertices (I used gizmos to see that they are there). However, I seem to be having trouble with the triangles, which do not connect all of the vertices. Here is the code for my mesh; could someone please tell me what I'm doing wrong? Thanks! :)
public void RenderMesh()
{
var vertices = new List<Vector3>();
var uvs = new List<Vector2>();
var tangents = new List<Vector4>();
for (int x = 0; x < 16; x++)
{
for (int z = 0; z < 16; z++)
{
Vector3 position = new Vector3(x, 0, z);
vertices.Add(position);
uvs.Add(new Vector2((float) x / 16, (float) z / 16);
tangents.Add(new Vector4(1, 0, 1, -1));
}
}
var triangles = new List<int>();
for (int x = 0, vrt = 0; x < 15; x++)
{
for (int z = 0; z < 15; z++, vrt++)
{
triangles.Add(vrt);
triangles.Add(vrt + 16);
triangles.Add(vrt + 1);
triangles.Add(vrt + 16);
triangles.Add(vrt + 17);
triangles.Add(vrt + 1);
}
}
var mesh = new Mesh();
mesh.name = "Terrain";
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.uv = uvs.ToArray();
mesh.tangents = tangents.ToArray();
mesh.RecalculateNormals();
_meshFilter.sharedMesh = mesh;
}
screen-shot-2021-07-21-at-31819-pm.png
(76.5 kB)
screen-shot-2021-07-21-at-31838-pm.png
(97.8 kB)
Comment
Best Answer
Answer by andrew-lukasik · Jul 21, 2021 at 09:23 PM
It was vrt++
fault. Calculate it as y*numVerticesX + x;
instead.
public void GenerateMesh ( int numVerticesX = 16 , int numVerticesZ = 16 )
{
var vertices = new List<Vector3>();
var normals = new List<Vector3>();
var uvs = new List<Vector2>();
for( int y=0 ; y<numVerticesZ ; y++ )
for( int x=0 ; x<numVerticesX ; x++ )
{
float tx = (float)x / (float)(numVerticesX-1);
float ty = (float)y / (float)(numVerticesZ-1);
vertices.Add( new Vector3(-0.5f+tx,0,-0.5f+ty) );
normals.Add( Vector3.up );
uvs.Add( new Vector2(tx,ty) );
}
var indices = new List<int>();
for( int y=0 ; y<(numVerticesZ-1) ; y++ )
for( int x=0 ; x<(numVerticesX-1) ; x++ )
{
int quad = y*numVerticesX + x;
indices.Add(quad);
indices.Add(quad+numVerticesX);
indices.Add(quad+numVerticesX+1);
indices.Add(quad);
indices.Add(quad+numVerticesX+1);
indices.Add(quad+1);
}
var mesh = new Mesh();
mesh.name = $"Terrain {mesh.GetHashCode()}";
mesh.vertices = vertices.ToArray();
mesh.triangles = indices.ToArray();
mesh.uv = uvs.ToArray();
mesh.normals = normals.ToArray();
_meshFilter.sharedMesh = mesh;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613040621im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Change Color of model from Down to up! 1 Answer
Multiple Cars not working 1 Answer
How do i create a Mesh in the middle of a Catmull spline? 0 Answers
Problem Creating a 2D Mesh 1 Answer
Distribute terrain in zones 3 Answers