# Procedural mesh triangulation wraps back on itself

Hello. I’m trying to triangulate an array of vertices into a mesh, However, my triangulation keeps wrapping back at the midpoint of my vertex array.
image?
Here i have an image illustrating the order in which the vertices are generated.

And below that is the result of the triangulation, which wraps back on the other side halfway through the vertex array. The vertices are shown as sphere gizmos.
image?
This is what my triangulation code looks like:

``````        _tris = new int[_count * 6];
for (int x = 0, tri = 0; x < _count; x++, tri += 6)
{
_tris[tri] = x;
_tris[tri+1] = x+1;
_tris[tri+2] = x+2;

_tris[tri+3] = x + 2;
_tris[tri + 4] = x + 1;
_tris[tri + 5] = x + 3;
}
mesh.triangles = _tris;
``````

I’m out of ideas as to why this occurs.
Any help would be greatly appreciated.

This is my vertex buffer code:

``````         _elements = new TempElement[_count];
GetComponent().mesh = mesh
= new Mesh();
for (int i = 0; i < _count; i++)
{
TempElement e = new TempElement();
e._index=i;
e._tempVal = 1.0f;
e._pos = new Vector3(transform.position.x +  (i+_spacing), transform.position.y,
transform.position.z);
_elements *= e;*
``````

}
mesh.vertices = _verts.ToArray();

Well, since you initialize your triangles array with `_count * 6` we would assume that _count contains the number of quads. Since you increment “x” by one each iteration and tri by 6, we assume you want to process a quad per iteration, which is fine. However your vertex indices are not correct that way. You have 2 vertices per quad. So instead of `x` you have to use `x*2` in all of your 6 lines.

edit

You have to do something like this:

``````int qCount = _count -1;
_tris = new int[qCount * 6];
for (int x = 0, tri = 0; x < qCount; x++, tri += 6)
{
_tris[tri] = x*2;
_tris[tri+1] = x*2 + 1;
_tris[tri+2] = x*2 + 2;

_tris[tri+3] = x*2 + 2;
_tris[tri + 4] = x*2 + 1;
_tris[tri + 5] = x*2 + 3;
}
mesh.triangles = _tris;
``````

Keep in mind that most shaders only render the front side of a mesh with some rare exception (usually particle shaders and such). That means only the front side of the mesh would be rendered. If you want to use a shader that can be affected by light and you want your mesh to be visible from both sides, you would need to double up the vertices, so you have one set for each side with the proper normal vectors for each side, or implement your own double sided shader. Though in most cases single sided is the way to go anyways

This is my vertex buffer code:

``````         _elements = new TempElement[_count];
GetComponent().mesh = mesh
= new Mesh();
for (int i = 0; i < _count; i++)
{
TempElement e = new TempElement();
e._index=i;
e._tempVal = 1.0f;
e._pos = new Vector3(transform.position.x +  (i+_spacing), transform.position.y,
transform.position.z);
_elements *= e;*
``````