1

I want to put some objects in a separate collection in my Python script. However, when I add an existing object to a new collection, it seems to exist in both the new collection and the main collection (where I put it to begin with) as shown in this figure the Cube exists in both the axis collection and the scene collection:

enter image description here

Here is my script:

import bpy
scene_collection = bpy.context.view_layer.layer_collection.children[0]
new_collection = bpy.data.collections.new("Axes")
bpy.context.scene.collection.children.link(new_collection)
obj=bpy.context.active_object
new_collection.objects.link(obj)
bpy.ops.mesh.primitive_cone_add()
#scene_collection.objects.unlink(obj)
bpy.context.view_layer.active_layer_collection = scene_collection 
bpy.ops.mesh.primitive_cone_add()  #add cone to original collection

The script adds the initial cube that appears in the 3D view to the new collection. When I was reading about collections, I was under the impression that new objects would automatically be added to the new collection, but the first cone that I add in the script is placed in the original collection.

So, my questions are, why is the Cube in both collections and how can I make sure it is only in one, and can I make the new collection active so that new objects are automatically added to it?

Duarte Farrajota Ramos
  • 59,425
  • 39
  • 130
  • 187
SJK
  • 169
  • 1
  • 7
  • After I asked this question, I found a similar one in StackExchange's Related list off to the side (https://blender.stackexchange.com/questions/192580/object-appears-twice-when-linking-it-to-a-collection?rq=1). From this answer, it seems like I was missing that the collection needs to be assigned a view_layer (probably not explained properly) before objects can be added to it. – SJK Mar 02 '21 at 16:28
  • 1

0 Answers0