Hey there,
Is there any way to enable and disable a single collection using blender python?
I’ve been searching for this as I’m working with many collections but couldn’t find it.
your time will be appreciated!
this isn’t done via the Collection object itself, but from a LayerCollection object:
https://docs.blender.org/api/current/bpy.types.LayerCollection.html
unfortunately accessing LayerCollections arbitrarily is a bit convoluted. I created a helper function that can assist with this.
def get_layer_collection(collection, view_layer=None):
'''Returns the view layer LayerCollection for a specificied Collection'''
def scan_children(lc, result=None):
for c in lc.children:
if c.collection == collection:
return c
result = scan_children(c, result)
return result
if view_layer is None:
view_layer = bpy.context.view_layer
return scan_children(view_layer.layer_collection)
To use it, just call get_layer_collection(your_collection)
and you’ll have a LayerCollection object you can use as you like. Just remember that the root scene collection does not have a corresponding LayerCollection.
Unfortunately if you’re linking a collection in more than one place in your scene, there is (AFAIK) not any reliable way to get to a specific layer collection. See my thread over on devtalk for more detail
For instance in this setup :
Collection 2 is linked in 3 different layer collections. You can mitigate it somehow with something like
def get_layer_collections(collection, view_layer=None):
if view_layer is None:
view_layer = bpy.context.view_layer
layer_collections_to_test = [view_layer.layer_collection]
while layer_collections_to_test:
layer_collection_to_test = layer_collections_to_test.pop(0)
layer_collections_to_test.extend(layer_collection_to_test.children)
if layer_collection_to_test.collection == collection:
yield layer_collection_to_test
Which returns all the potential layer collections. Then you can test if the layer collection has a specific parent or such if you need to.
And it has the added benefit of never triggering recursion limit which can happen with recursive functions. Note it returns a generator object, not a list so you may want to cast it to a list.
my_collection = bpy.data.collections["My Collection"]
my_layer_collections = list(get_layer_collections(my_collection ))
the question is Clear , it depended to Disabling and enabling a single Collection
what is my wrong ?
new_collection = bpy.data.collections.new("seq_1"))
addedCollection = context.scene.collection.children.link(new_collection)
context.view_layer.layer_collection.children.exclude(addedCollection)
after run that the collection still enabled
exclude
is an attribute on the layer collection itself, not a method you call on the parent collection.
context.view_layer.layer_collection.children["seq_1"].exclude = True