5
$\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$
0

1 Answer 1

8
$\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)

Look at ID users

It is most likely a lot quicker to run over the collections and check if they are in use by the scene. If a collection is linked anywhere in the hierarchy of a scene's collection tree, then the scene is a user of the collection.

>>> collections_in_scene = [
        c for c in D.collections 
        if C.scene.user_of_id(c)
    ]
>>> collections_in_scene
[bpy.data.collections['Collection 1'], bpy.data.collections['Collection 1 1'], bpy.data.collections['Collection 1 1 1']]
$\endgroup$
7
  • 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, 2020 at 14:20
  • 3
    $\begingroup$ They're often the same. coll = bpy.context.view_layer.layer_collection.collection $\endgroup$
    – batFINGER
    Feb 24, 2020 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, 2020 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, 2020 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, 2020 at 8:49

You must log in to answer this question.

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