14

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
Ray Mairlot
  • 29,192
  • 11
  • 103
  • 125
Steven Schell
  • 173
  • 1
  • 1
  • 4

1 Answers1

28

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

  • An Object can hold a reference to a Mesh. (or Curves, or other Types)
  • A Mesh only holds references to the objects that use it. (Actually, I think it only holds the count of objects that reference it.. not their names: maybe someone can correct me?)

In Object Mode

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.

In Edit Mode

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)

for 3.0

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)

mml
  • 443
  • 2
  • 9
zeffii
  • 39,634
  • 9
  • 103
  • 186
  • yes no reference just number of users, it will be redundant to store the relation on both sides – Chebhou Apr 24 '15 at 20:18
  • cool, don't recall ever really needing that information anyway.. just wondering! – zeffii Apr 24 '15 at 20:23
  • 1
    Thanks, this works great, the key is to do this in object mode. – Steven Schell Apr 27 '15 at 16:47
  • 1
    You may need to do bm.faces.ensure_lookup_table() before bm.faces[4].select = True # select index 4 – João Cartucho May 24 '19 at 14:44
  • 1
    I noticed that sometimes 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 – Harry McKenzie Jul 22 '22 at 00:35