How do I select a specific face within a mesh knowing its face index or vertex? I tried without success:
bpy.data.meshes.polygons[2].select=True #where the face index=2
The line below is invalid.
bpy.data.meshes.polygons[2].select = True
bpy.data.meshes
is a collection of all meshes in this .blend file, it doesn't have an attribute .polygons
. You are close though, you need to reference a specific mesh either via
mesh = bpy.data.objects['some_object_name'].data
# or
mesh = bpy.data.meshes['some_mesh_name']
Important to note here that Objects are not the same as Meshes
One way to select by face index is, go to Object Mode first then do
obj = bpy.context.active_object
obj.data.polygons[2].select = True
When you go back to Edit Mode you'll see the face is selected.
If you wanted to do that in Edit Mode, this might be unintuitive at first, but it involves a little more code. Blender comes with a useful collection of templates for mesh editing. The relevant template for this question can be found in Text Editor > Templates > Python > Bmesh Simple Edit Mode.
Below is a slight modification to that template, copy it to the Text Editor and press Run.
import bpy
import bmesh
obj = bpy.context.edit_object
me = obj.data
bm = bmesh.from_edit_mesh(me)
# notice in Bmesh polygons are called faces
bm.faces[4].select = True # select index 4
# Show the updates in the viewport
bmesh.update_edit_mesh(me, True)
import bpy
import bmesh
obj = bpy.context.edit_object
me = obj.data
bm = bmesh.from_edit_mesh(me)
# notice in Bmesh polygons are called faces
bm.faces[4].select = True # select index 4
# Show the updates in the viewport
bmesh.update_edit_mesh(me)
bm.faces.ensure_lookup_table()
before bm.faces[4].select = True # select index 4
$\endgroup$
Commented
May 24, 2019 at 14:44
obj.data.polygons[0].select = True
doesn't select the face. even when doing a loop for face in obj.data.polygons: face.select = True
. sometimes nothing happens, nothing is selected. but the bmesh way does always work. so something's wrong with obj.data.polygons[0].select
$\endgroup$