Low-level Origin to Geometry
You can:
- Sum the vert coordinates
- Make that the origin
- Shift the matrix back accordingly
import bpy
from mathutils import Matrix, Vector
scene = bpy.context.scene
mesh_obs = [obj for obj in scene.objects if obj.type == 'MESH']
for obj in mesh_obs:
d = obj.data
mw = obj.matrix_world
origin = sum((vert.co for vert in d.vertices), Vector()) / len(d.vertices)
T = Matrix.Translation(-origin)
d.transform(T)
mw.translation = mw @ origin
Alternatively, change your mesh creation class, such as not to use global coordinates.
Operators and Context
Operators use the context.
origin_set
will set the origin of all selected mesh objects, and can be run once on the selection, rather than per object.
See Python performance with Blender operators as to how this matters to performance.
Another part of context is the code in question. It's possible that changing the origin could be dealt with somewhere else, if you are, to quote:
...create all of the features that I want
However, without any idea of what the prior code is, here's a Test script.
It sets the origin of all mesh objects in the scene by passing them as an overridden context to the operator.
Blender 3.2+
import bpy
C = bpy.context
scene = C.scene
mesh_obs = [obj for obj in scene.objects if obj.type == 'MESH']
c = {"object" : mesh_obs[0],
"selected_objects" : mesh_obs,
"selected_editable_objects" : mesh_obs}
if mesh_obs:
with C.temp_override(**c):
bpy.ops.object.origin_set()
Blender 2.8+
import bpy
scene = bpy.context.scene
mesh_obs = [obj for obj in scene.objects if obj.type == 'MESH']
if mesh_obs:
bpy.ops.object.origin_set({
"object" : mesh_obs[0],
"selected_objects" : mesh_obs,
"selected_editable_objects" : mesh_obs,
})