3

I'm new to Blender. Tutorial information as recent as January this year appears to be out of date and I can't figure out how to create a new collection and add an object to it. The most recent relevant question I could find suggests this:

bus_collection = ops.collection.new(name="BusRoutes")
context.scene.collection.children.link(bus_collection)

and apparently at least needs to be changed to this:

bus_collection = ops.collection.create(name="BusRoutes")
etc.

which throws the error:

TypeError: CollectionChildren.link(): error with argument 1, "child" -  Function.child expected a Collection type, not set

The API entry for Collection operators is beyond sparse, and I'm not even sure what Add the object to an object collection that contains the active object even means.

May I ask someone to give me a minimal Blender 2.83 Python example of how to create a named collection and add an object to it? Many thanks.

brockmann
  • 12,613
  • 4
  • 50
  • 93
Richard
  • 143
  • 1
  • 4

1 Answers1

7

BlendDataCollections.new(name)

Recommend use the python console to figure out:

>>> D.collections.new(
new()
BlendDataCollections.new(name)
Add a new collection to the main database
...

>>> my_coll = D.collections.new("MyCollection") >>> C.scene.collection.children.link(my_coll)

Demo on how to create a new collection and add the default cube using CollectionObjects.link(object):

import bpy

New Collection

my_coll = bpy.data.collections.new("MyCollection")

Add collection to scene collection

bpy.context.scene.collection.children.link(my_coll)

Get cube object

obj = bpy.context.scene.objects.get("Cube")

if obj: # Link the cube my_coll.objects.link(obj)

brockmann
  • 12,613
  • 4
  • 50
  • 93
  • 1
    Thanks for the quick and helpful reply - works. Thanks also for the console tip. – Richard Jun 27 '20 at 17:39
  • On reflection: what is the difference between "ops.collection.create(name="BusRoutes")" and "data.collections.new("BusRoutes")"? – Richard Jun 28 '20 at 09:34
  • Cool @Richard That's the high level call (for the user) and always requires a certain context eg. the outliner, an object in selection or what not, related: https://blender.stackexchange.com/questions/2848/why-avoid-bpy-ops – brockmann Jun 28 '20 at 16:21
  • @Richard Notice this answer matches method used in question link. A simple test print will confirm Operators return a status set, for example {'FINISHED} or {'CANCELLED'} indicating the success of the "operation", not a reference to a newly created instance. The error message in question reflects this.. Changes made by operators are reflected in context. When successfully run the operator bpy.ops.collection.create(name="Foo") the newly created collection will contain the selected objects. It is not however linked to the context scene or given context. – batFINGER Jun 28 '20 at 17:37