2
$\begingroup$

I've put together a python script to select only the vertex with the minimum z-coordinate from a vertex selection in a mesh. The problem is that it works randomly, resulting in the correct selection only about once in four attempts. Most of the attempts result in none of the vertices getting selected. I've tested it on a square grid of unconnected vertices with neighbour correlated random z-coordinates.

I'm using blender 3.4.1 on MacOS Ventura 13.1

Sample file is here

Tis is the script:

import bpy

# Enter Object Mode
bpy.ops.object.mode_set(mode='OBJECT')

# Get the active mesh
mesh = bpy.context.object.data

# Get the selected vertices
selected_verts = [v for v in mesh.vertices if v.select]

# Find the vertex with the minimum z-coordinate
min_vert = min(selected_verts, key=lambda v: v.co.z)

# Enter Edit Mode
bpy.ops.object.mode_set(mode='EDIT')

# Deselect all vertices
bpy.ops.mesh.select_all(action='DESELECT')

# Enter Object Mode
bpy.ops.object.mode_set(mode='OBJECT')

# Select the min z vertex
min_vert.select = True

# Enter Edit Mode
bpy.ops.object.mode_set(mode='EDIT')
$\endgroup$
0

1 Answer 1

2
$\begingroup$

That's very interesting. I suspect that the pointer reference to min_vert gets disposed after you return to Object Mode. So just use the min_vert.index value to set the vertex select property directly like this:

bpy.context.object.data.vertices[min_vert.index].select = True

Here's the complete script:

import bpy

bpy.ops.object.mode_set(mode='OBJECT')
mesh = bpy.context.object.data

def get_min_z_vertex_index():
    selected_verts = [v for v in mesh.vertices if v.select]

    if len(selected_verts) <= 0:
        return -1

    min_vert = min(selected_verts, key=lambda v: v.co.z)
    return min_vert.index

index = get_min_z_vertex_index()

if index > -1:
    print("min-z vertex index: ", index)

    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.select_all(action='DESELECT')
    bpy.ops.object.mode_set(mode='OBJECT')
    bpy.context.object.data.vertices[index].select = True
    bpy.ops.object.mode_set(mode='EDIT')
    mesh.update()
else:
    print("No vertices selected!")
$\endgroup$
3
  • $\begingroup$ Thanks for the prompt reply. Your code works, but after a few times with different selections it gives the following error: Python: Traceback (most recent call last): File "/Users/joe/Documents/Blender/ChatGPT Generated Script Min-Max/ChatGPT Generated Script Min-Max - Corrected. blend/Text", line 13, in <module> ValueError: min( arg is an empty sequence $\endgroup$ Jan 19 at 16:46
  • 1
    $\begingroup$ it's an empty sequence if you don't select anything. you need to check if len(selected_verts):. see my updated script. $\endgroup$ Jan 21 at 1:14
  • 1
    $\begingroup$ Thanks. It works as expected. $\endgroup$ Jan 23 at 7:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .