We can enable or disable a collection that contains a specific object using the Blender Python API with a simple script. For example, let’s turn off the collection in which the currently selected object is.
First we need to get a pointer to the collection in which our object lies.
1 2 3 |
bpy.context.object.users_collection # (bpy.data.collections['Collection'], bpy.data.collections['Collection 5']) |
Since an object can reside in more than one collection, we get a list of pointers.
Let’s go through the resulting list in a loop and turn off all collections. We can turn off the scene collection (monitor icon) with the following code.
1 2 |
for col in bpy.context.object.users_collection: col.hide_viewport = True |
To turn off a collection on a view layer, we need to get a pointer to the view layer collection. We can use the following function for this:
1 2 3 4 5 6 7 8 9 |
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 |
Having a pointer to the view layer collection, we can turn its visibility on and off (checkbox and eye icons):
1 2 3 4 |
for col in bpy.context.object.users_collection: l_col = layer_collection(col.name) l_col.exclude = True l_col.hide_viewport = True |
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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 cols = bpy.context.object.users_collection for col in cols: col.hide_viewport = True l_col = layer_collection(col.name) l_col.exclude = True l_col.hide_viewport = True |
In order to return the collection by object back using the same script, we just need to replace True with False.