1
$\begingroup$

I am struggling to learn Blender, so bear with me...

Simple idea: select one (or more) vertices. Run the code, and all polygons connected to the vertex/vertices should be selected.

The code appears to work, in the sense that all effected polygons/faces get 'colored', therefore - in my mind - are 'selected'.

However, the very last line shows only False's for all polygons. I must be missing something here... enter image description here

import bpy
import bmesh

#----------        
def get_sel_vertices(me):
    sel_verts = [v for v in me.vertices if v.select]
    return sel_verts
#----------
# From selected vertices, select all polygons linked to those vertices (edit mode)
def vtx_get_sel_polygons(od):
    bm = bmesh.from_edit_mesh(od)
    poly = []
    for f in bm.faces:
        for v in f.verts:
            lf = v.link_faces
            if v.select:
                poly.append(f)        
    
    for p in poly:
        p.select = True
    
    bmesh.update_edit_mesh(ob.data)
    return len(poly) # Number of polys
#----------

ob = bpy.context.object
print("")

if ob.type != 'MESH':
    raise TypeError("Active object is not a Mesh")

# Get editmode changes
ob.update_from_editmode()

me = ob.data

vsel = get_sel_vertices(me)
        
if len(vsel):
    print('Selected v: ', len(vsel))
    
    polys = vtx_get_sel_polygons(me) # Select all connected polygons
    print('Selected p: ', polys)
    
    print([x.select for x in me.polygons]) # Every select shows up as False???

$\endgroup$

1 Answer 1

1
$\begingroup$

The reason why it's happening is because you are tying to get the vertices/polygons data from edit mode, which is not possible by directly accessing mesh components. There are several ways to fix it:

Change interpolation mode to OBJECT and back to EDIT(brute force)

import bpy
import bmesh
     
def get_sel_vertices(me):
    bpy.ops.object.mode_set(mode='OBJECT') # Go to OBJECT
    sel_verts = [v for v in me.vertices if v.select]
    bpy.ops.object.mode_set(mode='EDIT') # Go back
    return sel_verts

...
        
if len(vsel):
    print('Selected v: ', len(vsel))
    
    polys = vtx_get_sel_polygons(me)
    print('Selected p: ', polys)
    
    bpy.ops.object.mode_set(mode='OBJECT') # Go to OBJECT
    print([x.select for x in me.polygons])
    bpy.ops.object.mode_set(mode='EDIT') # Go back

Using BMesh(cleaner)


import bpy
import bmesh

bm = bmesh.from_edit_mesh(bpy.context.active_object.data)

sel_faces = [f for f in bm.faces if f.select]
sel_verts = [v for v in bm.verts if v.select]

Using BMesh method I assume that the object will be in Edit Mode. Hope it helps!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.