4
$\begingroup$

I'd like to get all collections in the current scene and can't find a way to do that. I found bpy.data.collections to get all collections stored in the blend and C.scene.collection.children to return the first level of sub-collections. However, I can't find out which collection is linked to each scene. I wonder if there is a simple way like iterating through the objects in context C.scene.objects?

Q: How to get all collections of the current scene?

$\endgroup$
7
$\begingroup$

Recursively walk the tree.

Similarly to https://blender.stackexchange.com/a/137866/15543 and Sorting Collections Alphabetically in the Outliner

import bpy

def traverse_tree(t):
    yield t
    for child in t.children:
        yield from traverse_tree(child)

coll = bpy.context.scene.collection

for c in traverse_tree(coll):
    print(c.name)
| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ This solution is "WOW", but I wonder one thing, what does it change to use C.view_layer.layer_collection.collection with C.scene.collection? $\endgroup$ – Noob Cat Feb 24 at 14:20
  • 3
    $\begingroup$ They're often the same. coll = bpy.context.view_layer.layer_collection.collection $\endgroup$ – batFINGER Feb 24 at 14:29
  • $\begingroup$ What is the difference between the bpy.context.scene.collection and bpy.data.collections because with the second one in my case I am getting some extra collections from the ones that are visible in the outliner. $\endgroup$ – ttsesm Sep 25 at 8:12
  • $\begingroup$ A blend can appear totally empty. The data we see is linked to a scene. Just as an object with no parent really has the scene as a parent, the scene collection is the root of collections in a scene without the need to also define it in bpy.data.collections $\endgroup$ – batFINGER Sep 25 at 8:25
  • 1
    $\begingroup$ Use context.collection would be my suggestion. Or to be sure to be sure context.collection or scene.collection Unless I'm creating objects rarely or never use bpy.data eg if you are interested in an object "Foo" scene.objects.get("Foo") is in the scene, whereas bpy.data.objects.get("Foo") may not be. Similarly with collections. $\endgroup$ – batFINGER Sep 25 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.