Add an empty object and set as parent
Rather than edit into your code I have added an example of how to add objects and set to have same parent. Have used "dummy" version of your add_mesh_to_scene
to illustrate.
Uses the default cube mesh as a proxy for the imported mesh. Adds an empty at the cursor location and num_objects = 4
as the children of that empty. Set the inverse parent matrix to position the imported mesh objects where they would be without an empty parent at cursor location.
import bpy
from mathutils import Matrix
context = bpy.context
scene = context.scene
num_objects = 4
def create_mesh():
# dummy method returns def cube mesh
return bpy.data.meshes.get("Cube")
def add_mesh_to_scene(scene, mesh):
obj = bpy.data.objects.new(mesh.name, mesh)
scene.objects.link(obj)
return obj
if num_objects:
# code to add empty parent
mt = bpy.data.objects.new("Handle", None)
scene.objects.link(mt)
mw = Matrix.Translation(scene.cursor_location)
mt.matrix_world = mw
# return as active
scene.objects.active = mt
mwi = mw.inverted()
for i in range(num_objects):
me = create_mesh()
ob = add_mesh_to_scene(scene, me)
ob.parent = mt
# setting this keeps them in import locs.
ob.matrix_parent_inverse = mwi
# set some loc to visualize
ob.location.x += 1.1 * i * ob.dimensions.x
# return as selected
ob.select = True
# update scene once.
scene.update()