We can’t set a collection active through the Blender Python API in one step. The “bpy.context.collection” property is read-only, and the “bpy.context.view_layer.active_layer_collection” has a “LayerCollection” type that cannot be set with the standard “Collection” type. To assign an active collection, we need to find the View Layer collection from the desired base collection and already set it as active.
First, let’s define a function that,will find Vliew Layer collection by name.
1 2 3 4 5 6 7 8 9 10 11 |
import bpy def layer_collection(name, _layer_collection=None): if _layer_collection is None: _layer_collection = bpy.context.view_layer.layer_collection if _layer_collection.name == name: return _layer_collection else: for l_col in _layer_collection.children: if rez := layer_collection(name=name, _layer_collection=l_col): return rez |
In our function, we have defined two input parameters:
name – the name of the collection to find
_layer_collection – an optional parameter, a collection inside which we are looking for the desired one. If None, the search is performed from the scene’s base collection.
The function searches through the View Layer collections.
Inside the function, we first check if the current collection is the one we are looking for, if so, we return it, and if not, we search through all its children collections by calling our function recursively.
If the View Layer collection with the given name is found, let’s make it active:
1 2 3 4 |
col = layer_collection(name='Collection 2 1') if col: bpy.context.view_layer.active_layer_collection = col |
Now check that the desired collection has really become active:
1 2 3 |
print('active collection: ', bpy.context.collection) # active collection: <bpy_struct, Collection("Collection 2 1") at 0x000001665E366B08> |