First you need to retrieve the view layer you'd like to modify. The view layers in the scene can be accessed through bpy.context.scene.view_layers
or if you want to access view layers of other scenes you can use bpy.data.scenes["Name of the scene"].view_layers
.
In order to exclude a specific collection the LayerCollection
has to be accessed, because that is where the exclude
property is stored. While iterating over the children of the master layer collection from the view layer, we can check for each entry if it matches the collection that we want to include. If it doesn't, it can be excluded through its LayerCollection
and otherwise be included.
import bpy
def include_only_one_collection(view_layer: bpy.types.ViewLayer, collection_include: bpy.types.Collection):
for layer_collection in view_layer.layer_collection.children:
if layer_collection.collection != collection_include:
layer_collection.exclude = True
else:
layer_collection.exclude = False
if __name__ == "__main__":
view_layer = bpy.context.scene.view_layers["View Layer"]
collection_include = bpy.data.collections["Collection"]
include_only_one_collection(view_layer, collection_include)