Better Way to Get Children and Grandchildren?

Hi,

Is there a better way to get the children and grandchildren of a selected object?

My code below works but it does not scale properly. I need to know how many children/grandchildren I have to be able to determine how many for loops I execute.

import bpy


sel_obj = bpy.context.active_object

obj_list = []

for child01 in sel_obj.children: 
    obj_list.append(child01)
    
    for child02 in child01.children:
        obj_list.append(child02)
        
        for child03 in child02.children:
            obj_list.append(child03)
            
            
print (obj_list)

Ben

1 Like

You can use a while-loop and sets.

import bpy

obj = bpy.context.object

all_children = set(obj.children)
pool = all_children.copy()

while pool:
    child = pool.pop()
    all_children.add(child)
    pool.update(child.children)

for c in all_children:
    c.select_set(True)
1 Like

Thanks @iceythe!
What an efficient algorithm, never thought of using a set.

Thanks for sharing! :slight_smile: