Get active selected vertex

Hello,

I could not find how to obtain the active selected vertex using the API (the vertex which has been selected last and is shown as white vertex by default). Any hints are highly appreciated (just the function name is sufficient).

Thanks
blackno666

in “old” api there is only polygons.active, but not the same for edges and vertices.

So you gotta use the bmesh module:

import bpy, bmesh

def bm_vert_active_get(ob):
    if ob.mode != 'EDIT':
        return

    bm = bmesh.from_edit_mesh(ob.data)
    for elem in reversed(bm.select_history):
        if isinstance(elem, bmesh.types.BMVert):
            return elem

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

Interesting approach. I am using 2.65.0 r53189 and also tried 2.65.10 r54336, but when running your code on a new scene with a cube in Edit mode, some vertices selected, I get “<BMVert dead at 0x000000000…>”

But if I use


        if isinstance(elem, bmesh.types.BMVert):
            print(elem)
            print(elem.co)
            return elem

then the correct coordinate will be printed. I don’t understand this behavior. Is this a python thing or a blender problem?

that’s weird, but i found the problem:
bm is a local variable of the function and doesn’t exist in the calling scope, therefore bm gets freed…

you can solve it like this for instance:


import bpy, bmesh


def bm_vert_active_get(bm):
    for elem in reversed(bm.select_history):
        if isinstance(elem, bmesh.types.BMVert):
            return elem


def print_active_vert():
    ob = bpy.context.object
    if ob.mode != 'EDIT':
        return
    
    bm = bmesh.from_edit_mesh(ob.data)
    print(bm_vert_active_get(bm))


print_active_vert()

could also use a global var, but it’s nicer this way