1
$\begingroup$

do you know how I can iterate through all the vertices of a mesh, and add a new Empty object as a hook to them via using a script? Like you would do by clicking on them in Edit Mode and then pressing Ctrl+H.

I'm trying to achieve this by the following code unsuccessfully so far:

# I import the bpy and do various things here which work, but the below one doesn't

current_obj = bpy.context.object

for vert in current_obj.data.vertices:          
    vert.hook_add_newob()

Thank you for the support in advance!

$\endgroup$
2
  • $\begingroup$ bpy.ops.object.hook_add_newob() $\endgroup$
    – yhoyo
    Feb 22 '16 at 15:43
  • $\begingroup$ Yes I tried this already and it also doesn't work. I can't even read the error message just that "Phython script fail, look in the console" - but there is nothing in the console... $\endgroup$
    – MatX
    Feb 22 '16 at 15:58
3
$\begingroup$

Try this:

import bpy, bmesh

# Create a persistent reference to current object
current_obj = bpy.data.objects[ bpy.context.object.name ]

bpy.ops.object.mode_set( mode = 'EDIT' ) # Go to edit mode

bm = bmesh.from_edit_mesh( current_obj.data )

for i in range( len( bm.verts ) ):
    bpy.context.scene.objects.active = current_obj
    bpy.ops.mesh.select_all( action = 'DESELECT' ) # Deselect all vertices
    bm = bmesh.from_edit_mesh( current_obj.data )
    bm.verts.ensure_lookup_table()
    v  = bm.verts[i]
    v.select = True
    bm.select_flush( True )
    bpy.ops.object.hook_add_newob()

bpy.ops.object.mode_set( mode = 'OBJECT' )     # Back to object mode
$\endgroup$
0
1
$\begingroup$

It is now possible without edit mode nor operators.

Can add a modifier assign it vertices and an object without requiring to be in edit mode, or running any operators.

Have lazily added the empty with add empty operator below, but could be replaced with existing objects or bpy.data.objects.new(name, None) and linking to a collection linked to scene. (Adding an object without operators has been well covered on BSE)

import bpy

context = bpy.context
scene = context.scene
tri = context.object
if tri and tri.type == 'MESH':
    me = tri.data
    for v in me.vertices:
        name = f"Vert_{v.index}"
        bpy.ops.object.empty_add(
                location=tri.matrix_world @ v.co
                )
        mt = context.object
        mt.name = name
        hm = tri.modifiers.new(
                name=name,
                type='HOOK',
                )
        hm.object = mt
        hm.vertex_indices_set([v.index]) 

Used in answer here https://blender.stackexchange.com/a/197166/15543

$\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.