- Home /
Finding the Vertices that make a face
I am looking to change the vertex colors on each face of an object to the same color. To do this, I need to know which vertices make up the triangle face. I have tried using Mesh.triangles, but they do not seem to list the order in which each vertice makes a face. In fact when I assign it to an array they count from 0, 1, 2, 3, 4. . .
Is there a way that I can determine which vertices make up a face? Thank you.
Answer by Bunny83 · Jun 11, 2014 at 01:17 AM
In the past it was quite simple since a Mesh only contained triangles. So the indices are used in groups of 3 to define 1 triangle. Now a Mesh can contain quads, triangles, lines, linestrips or points.
The usual way (which does still work if the mesh contains triangles) is:
//C#
Vector3[] vertices = mesh.vertices;
Color[] colors = mesh.colors;
int[] indices = mesh.triangles;
int triangleCount = indices.Length / 3;
for (int i = 0; i < triangleCount; i++)
{
Vector3 V1 = vertices[indices[ i*3 ]];
Vector3 V2 = vertices[indices[ i*3+1 ]];
Vector3 V3 = vertices[indices[ i*3+2 ]];
Color C1 = colors[indices[ i*3 ]];
Color C2 = colors[indices[ i*3+1 ]];
Color C3 = colors[indices[ i*3+1 ]];
// [...]
// apply changes and assign back
vertices[indices[ i*3 ]] = V1;
// [...]
}
// finally you have to assign the changed array(s) back
mesh.vertices = vertices;
mesh.colors = colors;
If your mesh contains Quads you might want to check a submeshes topology if it contains quads or triangles and then changen the above to read 4 indices per face instead of 3. Of course you have to use mesh.GetIndices instead of mesh.triangles in that case.
ps: If your triangle array just contains a gapless enumeration of numbers (0,1,2,3,4,5, ...), that just means that no vertex is shared between triangles. If you want to change the color of only one face that's actually a requirement. Otherwise, if a vertex is shared between two triangles, both triangles would be affected since they use the same position / color / normal ...