I need some help with a script to convert big CAD-files with 80+ collections. The collections need to be changed to a empties with sub-empties and objects. And they need to maintain the hierarchy. I'm not good in programming and I have no expierience in Blender-coding.
I spend 2 days for searching and stitching example codes together and I already can convert the collections with my script.
I'd like to:
- make an instance from a collection
- make the instance real
- delete the collection
(all this from the last collection up to the fist, to maintain hierarchy)
The problem is that the instances are placed in the main-collection and not in the corresponding collection, and so the hierarchy is broken.
Can someone tell me how to tell blender to place the instance in the corresponding collection?
import bpy print() print() print("---------START------------") def traverse_tree(t): yield t for child in t.children: yield from traverse_tree(child) # Recursivly transverse layer_collection for a particular name def recurLayerCollection(layerColl, collName): found = None if (layerColl.name == collName): return layerColl for layer in layerColl.children: found = recurLayerCollection(layer, collName) if found: return found coll = bpy.context.scene.collection # start @ top-collection list = for c in traverse_tree(coll): list.append(c.name) # remove unwanted collections list.remove('Collection') # Camera & Light list.remove('Master Collection') # Master Collection list.pop(0) # root collection from imported scene # start from bottom to top list.reverse() for entity in list: print("Verarbeite: " + entity) source_collection = bpy.data.collections[entity] instance_obj = bpy.data.objects.new(name=entity, object_data=None) instance_obj.instance_collection = source_collection instance_obj.instance_type = 'COLLECTION' layer_collection = bpy.context.view_layer.layer_collection # start on top parent_collection = recurLayerCollection(layer_collection, entity) parent_collection = bpy.context.view_layer.layer_collection parent_collection.collection.objects.link(instance_obj) bpy.data.objects[entity].select_set(True) # select instance bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # convert to object(meshes & emptys) bpy.data.collections.remove(source_collection) # delete original collection print()
The extensions on the names (.001) are not important, I filter them later.