# Fetching triangles from a 3D Mesh

As @yoyo commented there - "Get point i for triangle j with p = mesh.vertices[mesh.triangles[i + 3 * j]] -- i is 0, 1, 2 for the three corners of the triangle, and j goes from 0 to mesh.triangles.length/3 - 1."

Basicly, this is what I have made so far for triangle fetching, but it looks like the function isn't working as it should:

``````// function to gather all the triangles on mesh
private function GatherTriangles(mesh : Mesh, triangle : int){
var p : Vector3 = Vector3.zero;
for(var i = 0; i < 3; i++){
p = mesh.vertices[mesh.triangles[i + 3 * triangle]];
}
return p;
}

// Start function, executes gathering, counts results and stuff
function Start () {
var mesh : Mesh = GetComponent(MeshFilter).mesh;
for(var n = 0; n < mesh.triangles.length; n++){
trianglePoints.Push(GatherTriangles(mesh, j));
j = (mesh.triangles.length / 3) - 1;
}
print(trianglePoints); // print #1
print(trianglePoints.length); // print #2
}

``````

Result:

print #1: (0.0, 0.0, 0.3),(0.0, 0.0, 0.4),(0.0, 0.0, 0.4) and continues so on, no values are changed anymore.

print #2: 12060

Used on Standard Assets -> Construction Worker Mesh, has 4020 tris (4020 * 3 = 12060, so there is some kind of relation between all that hassle there).

Actually, have no idea what is causing this mess, and I have no idea what should be the format for `p`.

Hope you guys can help me, thanks in advance!

Given you have a mesh, you can get each individual corner of the triangles like this:

``````for (int i = 0; i < mesh.triangles.Length; i += 3)
{
Vector3 p1 = mesh.vertices[mesh.triangles[i + 0]];
Vector3 p2 = mesh.vertices[mesh.triangles[i + 1]];
Vector3 p3 = mesh.vertices[mesh.triangles[i + 2]];
}

``````

The triangles property contain the indices to the vertices. So we go through each triplet of indices to look up the vertex index. We then use the vertex index to find the actual vertex.

Just to clarify what is returned from the triangles and vertices, consider this small example:

``````// Get the first vertex index which is the first vertex in the first triangle.
int vertexIndex = mesh.triangles[0];

// Then get the vertex from a vertex index.
Vector3 vertex = mesh.vertices[vertexIndex];

``````

One thing off the bat is your gather func will always return just the last vertex in the given triangle