1
$\begingroup$

I'm trying to do something similar as in this post, but instead of all dimensions from each object I want to know to which collection they belong.

The part of the code I changed was:

selection = bpy.context.selected_objects

# iterate through the selected objects
for sel in selection:
    # get collection to which the object belongs
    col = bpy.context.collection
    # write the selected object's name and dimensions to a string
    result += "%s, %s" % (sel.name, col.name)

However, this seems to loop over the collections that are inside of the selected objects instead of the other way around. How do I change my code to see the collection the objects belongs to?

$\endgroup$
2
  • $\begingroup$ Pretty close but the collection name would be the same for all objects (context.collection is the active one). How to get the collection of the object: blender.stackexchange.com/a/134789/31447 $\endgroup$
    – brockmann
    Commented Jul 23, 2021 at 15:32
  • $\begingroup$ That works, thank you! $\endgroup$
    – Laura
    Commented Jul 23, 2021 at 15:49

1 Answer 1

0
$\begingroup$

check this out:

import bpy


for eachCol in bpy.data.collections:
    
    print("Collection:", eachCol.name)
    
    for eachObject in eachCol.objects:
        
        print("  ", eachObject.name)

Test result:

enter image description here

or if you only want the info about the selected objects:

import bpy

selected = bpy.context.selected_objects

for eachSel in selected: 

    for eachCol in bpy.data.collections:
        for eachObject in eachCol.objects:
            
            if eachObject == eachSel:
            
                print(eachObject.name, "is in", eachCol.name)

test result:

enter image description here

$\endgroup$

You must log in to answer this question.

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