OBJ Importing
The script imports .obj files from a specified folder and pastes them to the scene by collections. Import.py creates the empty collections and temporary moves objects to data-block. Paste.py moves objects from data-block to the scene and distributes them by collections. Also added the scale and rotation corrections.
The important moment that can help with the question happens here: at first the objects creates from the meshes data-block using bpy.data.objects.new(mesh.name, mesh)
and continue store in the objects data-block (not linked with the scene). After they are distributed across the collections using the name matching.
Import.py
import bpy
import os.path as path
import glob
root = path.abspath(path.join('' ,".."))
files = glob.glob(root + '\*.obj')
for f in files:
bpy.ops.import_scene.obj(filepath=f)
name = path.split(f)[1].replace('.obj', '')
col = bpy.data.collections.new(name)
bpy.context.scene.collection.children.link(col)
indexes = len([ob for ob in bpy.context.selected_objects if ob.tag == False])
for i in range(indexes):
bpy.context.selected_objects[i].name = '{}-{}'.format(name, i)
bpy.context.selected_objects[i].data.name = '{}-{}'.format(name, i)
bpy.ops.collection.objects_remove_all()
for ob in bpy.data.objects:
bpy.data.objects.remove(ob)
for m in bpy.data.materials:
m.user_clear()
bpy.data.materials.remove(m)
for mesh in bpy.data.meshes:
ob = bpy.data.objects.new(mesh.name, mesh)
ob.active_material_index = 0
for i in range(len(ob.material_slots)):
bpy.ops.object.material_slot_remove({'object': ob})
Paste.py
import bpy
from mathutils import Vector, Euler
from math import radians
for ob in bpy.data.objects:
for col in bpy.data.collections:
if col.name == ob.name.split('-')[0]:
col.objects.link(ob)
for ob in bpy.context.scene.objects:
ob.scale = Vector=((0.5, 0.5, 0.5))
ob.rotation_euler = Euler((radians(180), 0.0, 0.0), 'XYZ')
Note: DON’T use a symbol -
in names