Blender Python – Accessing mesh triangles

Software:
Blender 2.81 | Python 3.74

By default, mesh triangles are not accessible to Python in Blender.
When accessing the mesh triangles is needed, they must be calculated first using the ‘calc_loop_triangles’ Mesh object method.
Before the calc_loop_triangle method has been called, the loop_triangles property of the Mesh object will reference a empty collection.
After calling the calc_loop_triangles method, the loop_triangles property will reference a collection of MeshLoopTriangle objects, in which the vertices property will hold an array of 3 integers that are the indices of the triangle vertices.

The following example script creates and places sphere objects at the centers of the cube’s triangles:

import bpy
mesh = bpy.data.objects['Cube'].data
mesh.calc_loop_triangles()
     for tri in mesh.loop_triangles:
     tri_center = (mesh.vertices[tri.vertices[0]].co * 0.333) +\
                  (mesh.vertices[tri.vertices[1]].co * 0.333) +\
                  (mesh.vertices[tri.vertices[2]].co * 0.333)
     bpy.ops.mesh.primitive_uv_sphere_add(radius=0.1,
                                          enter_editmode=False, 
                                          location=tri_center)

* note that when copying and pasting a script from this example, the indentation may not be pasted correctly.

Download and example file here

Annotation 2019-11-23 224800.jpg