User:Sybren/SfA/collections-API
< User:Sybren | SfA
Scripting for Artists: Collections API
- First investigations: Python console + using TAB
C.scene.coll<tab>
C.scene.collection.children.<tab>
→ nonew()
method, but do seelink()
method.- Conclusion: create a new collection somehow, and link it to the scene master collection.
bpy.data.coll<tab>
→bpy.data.collections
→ add period →bpy.data.collections.<tab>
:new()
method.
Create collection
import bpy
# We do that here now, but in your own code, use the given `context` parameter if possible.
C = bpy.context
# Create in bpy.data:
collection = bpy.data.collections.new('DEMO')
Pitfall:
>>> bpy.data.collections.new('DEMO')
bpy.data.collections['DEMO']
>>> bpy.data.collections.new('DEMO')
bpy.data.collections['DEMO.001']
Always use the returned collection, and do NOT use bpy.data.collections[the name I just used]
expecting it is the same.
Link to scene, rename, add object
C.scene.collection.children.link(collection) # check outliner
collection.name = 'SfA'
collection.objects.link(C.object) # link active object to collection
Move object from one collection another
coll_from = bpy.data.collections['SfA']
coll_to = bpy.data.collections.new('Target')
C.scene.collection.children.link(coll_to)
# Try with one object first:
ob = coll_from.objects[0]
coll_to.objects.link(ob)
coll_from.objects.unlink(ob)
# Indent and add `while` loop:
while coll_from.objects:
ob = coll_from.objects[0]
coll_to.objects.link(ob)
coll_from.objects.unlink(ob)
# And maybe remove the now-empty collection.
# Apparently this works even when it's linked to other collections.
bpy.data.collections.remove(coll_from)
Address objects by name
>>> coll_to.objects['Suzanne']
bpy.data.objects['Suzanne']
Do something with all objects in a collection
print(f'Finding all objects in {collection.name} (including nested collections):')
for ob in collection.all_objects:
# Do anything with the objects here, but do not change their collection!
print(f' - {ob.name} has data {ob.data.name}')