- Home /
Triangles on my mesh don't show
I am trying to fill in a plane of vertices with triangles but the triangles do not show on my mesh. Is there anything I am doing wrong? Here is the code that does that:
private void Generate()
{
for (int z = 0; z < chunkWidth; z++)
{
for (int x = 0; x < chunkWidth; x++)
{
float simplex1 = noise.GetSimplex(x * 0.8f, z * 0.8f) * 10;
float simplex2 = noise.GetSimplex(x * 3f, z * 3f) * 10 * (noise.GetSimplex(x * 0.3f, z * 0.3f) + 0.5f);
float y = simplex1 + simplex2;
// Instantiate(cube, new Vector3(x, y, z), Quaternion.identity);
verts.Add(new Vector3(x, 0, z));
}
}
int v = 0;
int t = 0;
for (int z = 0; z < chunkWidth; z++)
{
for (int x = 0; x < chunkWidth; x++)
{
tris.Add(v + 0);
tris.Add(v + chunkWidth + 1);
tris.Add(v + 1);
tris.Add(v + 1);
tris.Add(v + chunkWidth + 1);
tris.Add(v + chunkWidth + 2);
v++;
t += 6;
}
v++;
}
UpdateMesh();
}
private void UpdateMesh()
{
mesh.vertices = verts.ToArray();
mesh.triangles = tris.ToArray();
mesh.RecalculateNormals();
MeshFilter filter = GetComponent<MeshFilter>();
filter.mesh = mesh;
}
Answer by Bunny83 · Jan 08, 2021 at 02:00 AM
Your triangles are wrong your indices in the next row are off by 1. You should not add 1 and 2 but instead add 0 and 1. You also create too many quads. If you have a field of x x vertices you only have (x-1) (x-1) quads between them. It should look something like this:
for (int z = 0; z < chunkWidth-1; z++)
{
for (int x = 0; x < chunkWidth-1; x++)
{
tris.Add(v);
tris.Add(v + chunkWidth);
tris.Add(v + 1);
tris.Add(v + 1);
tris.Add(v + chunkWidth);
tris.Add(v + chunkWidth + 1);
v++;
t += 6;
}
v++;
}
chunkWidth is the number of vertices in one row. So adding this count to an index will shift the row. Just imagine a small case, say a 3x3 vertex grid. It means the width and height are both 3. There are 3 vertices in each row. The indices of the first row are 0, 1 and 2. The second row has 3, 4 and 5. So if you are at index 0 you have to add 3 to get to the same index in the next row, not 4. It should also be clear that a 3x3 vertex field has only 4 quads between those vertices. The quads are in a 2x2 area between the vertices. If you can not imagine such things in your head, I highly recommend to grab pen and paper and draw the arrangement. It really helps visualising the problem. Keep in mind that triangles in Unity need clockwise winding in order to be visible.
If it's still not visible, are you sure you have a MeshRenderer on your gameobject and a proper material assigned?
Your answer
![](https://koobas.hobune.stream/wayback/20220613022906im_/https://answers.unity.com/themes/thub/images/avi.jpg)