2
$\begingroup$

I'm trying to write a Python script that parses through the outliner to join meshes that have a hierarchy. Similar to the manual option to right-click an object in the outliner, do a "Select Hierarchy" and then do a CTRL-J to join the selected.

This is what I have so far, but I think I'm lacking API knowledge to get it right:

import bpy

scene = bpy.context.scene

print("#################### JOIN HIERARCHIES ###################")

bpy.ops.object.select_all(action='DESELECT') # Deselecting all

bpy.context.area.type = 'OUTLINER' 

for ob in scene.objects:

    #scene.objects.active = ob

    #print("--", ob.name)

    if ob.type == 'MESH':

        bpy.ops.outliner.object_operation(type='SELECT_HIERARCHY')
        bpy.ops.object.join()
        bpy.ops.object.select_all(action='DESELECT') # Deselecting all

print("################## END JOIN HIERARCHIES #################")

Thanks in advance for your help!

$\endgroup$

1 Answer 1

4
$\begingroup$

If an object has no parent its parent attribute will be None. If it has children its len(ob.children) will be greater than 0.

Then we can select all top level obs as having no parent and children, select all their children, deselect non meshes and join

import bpy

context = bpy.context
scene = context.scene
# select scene objects that have no parent and children
obs = [o for o in scene.objects if not o.parent and len(o.children)]

for o in obs:
    # deselect all
    bpy.ops.object.select_all(action='DESELECT')
    scene.objects.active = o
    # select all children recursively
    bpy.ops.object.select_grouped(type='CHILDREN_RECURSIVE')
    # select parent too
    o.select = True
    for so in context.selected_objects:
        #deselect if not mesh
        if so.type != 'MESH':
            so.select = False
    #if there are some mesh children
    if len(context.selected_objects):
        scene.objects.active = context.selected_objects[0]        
        # join them
        bpy.ops.object.join()
$\endgroup$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .