I currently have a method that does:

self.myCol = bpy.data.collections.new(self.collection_name)

This method creates and adds a new collection to the outliner. Next, I want to create a bunch of cubes and add those cubes to the collection. How can I tell blender to create objects only within that particular collection?

Something like:

bpy.ops.mesh.primitive_cube_add(collection='name', size=2, location=(0, 0, 0))

Obvious cube_add doesn't have the param for it, so what's the proper way to do this?


Your answer is actually wrong.

If your active collection is another as the main collection, when running your script the object will not be removed from this.

import bpy

# our created cube is the active one
obj = bpy.context.active_object
# Remove object from all collections not used in a scene
# add it to our specific collection

About remove all: https://docs.blender.org/api/blender2.8/bpy.ops.collection.html#bpy.ops.collection.objects_remove_all

| improve this answer | |

I figured it out. C is bpy.context btw.

self.master_collection = bpy.context.scene.collection

self.layer_collection = bpy.data.collections[ collection_name ]

for i in range(...):

    bpy.ops.mesh.primitive_cube_add(size=2, view_align=False, enter_editmode=False, location=(0, 0, 0))
    # Create the cubes

    self.layer_collection.objects.link(C.object) #link it with collection

    self.master_collection.objects.unlink(C.object) #unlink it from master collection
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.