I'm trying to write a quick script that will work on all selected objects:
- Start in object mode
- Go into edit mode
- Set the 3d cursor location to the selected vertices
- Go back to object mode
- Set the origin of the object to the 3d cursor.
I can't seem to get the cursor to selected part to work properly :/ (step 3)
UPDATE
got this script to work if anyone has any improvements, please suggest: https://pastebin.com/krmzC8Kh
import bpy
import mathutils
# Store the active object and mode
active_object = bpy.context.active_object
active_mode = bpy.context.mode
# Iterate through selected objects
for obj in bpy.context.selected_objects:
# Select the object and make it active
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
# Switch to object mode
bpy.ops.object.mode_set(mode='OBJECT')
# Set the object as the active object
bpy.context.view_layer.objects.active = obj
# Switch to edit mode
bpy.ops.object.mode_set(mode='EDIT')
# Get the selected vertices
selected_verts = []
mesh = obj.data
for vertex in mesh.vertices:
if vertex.select:
selected_verts.append(vertex.co)
# Check if there are any selected vertices
if selected_verts:
# Calculate the average position of selected vertices
avg_position = [sum(v[i] for v in selected_verts) / len(selected_verts) for i in range(3)]
# Transform the average position from local space to global space
global_position = obj.matrix_world @ mathutils.Vector(avg_position)
# Set the 3D cursor location to the calculated global position
bpy.context.scene.cursor.location = global_position
# Switch back to object mode
bpy.ops.object.mode_set(mode='OBJECT')
# Set the origin of the object to the 3D cursor location
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
# Deselect the object
obj.select_set(False)
# Restore the active object and mode
bpy.context.view_layer.objects.active = active_object
bpy.ops.object.mode_set(mode=active_mode)