Scripting: Collections
Every scene has a master collection:
# the master collection
bpy.context.scene.collection
# get a list of objects in that collection
list(bpy.context.scene.collection.objects)
# get EVERYTHING in that scene
list(bpy.context.scene.collection.all_objects)
Collections are stored in the bpy.data.collections class:
# get the collection named "demo"
col=bpy.data.collections["demo"]
# what's in there?
list(col.objects)
You can create new collections, add collections or objects to that collection.
# important: the name has to be unique, or a unique name is given
col=bpy.data.collections.new("my collection")
# but it's not visible in the scene
# as it's not linked to the master collection
bpy.context.scene.collection.children.link(col)
# same with objects
bpy.ops.mesh.primitive_cube_add()
myCube=bpy.context.scene.objects.get("Cube")
col.objects.link(mycube)
# nah, not cool
col.objects.unlink(mycube)
You can set the visibility settings:
col.hide_select=True
col.hide_viewport=True
col.hide_render=True
col.holdout=True
col.indirect_only=True # not working?
Objects and Collections
The relation to a collection is stored in users_collection:
import bpy
obj=bpy.context.active_object
print(obj.users_collection.name)
Change an objects collection like this:
def set_collection(obj, coll):
for coll in obj.users_collection:
coll.objects.unlink(obj)
coll_target.objects.link(obj)