2

I'm really new to Blender, and want to script an octahedron with all parts neatly placed inside its own collection.

But somehow, when I create a new collection and link objects to my newly created collection, the objects also stay linked to the original "Scene Collection".

In a new scene, when I drag and drop a manual added object to the scene, that I than add to the personal collection this does not happen?

enter image description here enter image description here

myCollections = bpy.data.collections

colOcta = myCollections.new('col_Octahedron')
bpy.context.scene.collection.children.link(colOcta)

vtxAmount = 6
vtxPositions = [(0, 0, 10), (10, 0, 0), (0, 10, 0), (-10, 0, 0), (0, -10, 0), (0, 0, -10)]
for i in range(vtxAmount):
    iSolve = i + 1

    nowPos = vtxPositions[i]
    myX = nowPos[0]
    myY = nowPos[1]
    myZ = nowPos[2]
    #print(myX)
    newObj = bpy.ops.mesh.primitive_uv_sphere_add(radius=1, enter_editmode=False, location=(myX, myY, myZ))

    myObj = bpy.context.object
    myObj.name = "obj_Sphere%s" %iSolve
    myObj.data.name = "dat_Sphere%s" %iSolve
    grpOcta.objects.link(myObj)
Ray Mairlot
  • 29,192
  • 11
  • 103
  • 125
Shakena
  • 21
  • 2

1 Answers1

3

An object can be part of an arbitrary number of collections. Adding an object to a collection does not remove it from any other collection it may be a part of.

When you use an operator to instantiate an object, is is automatically added to the active collection. In your case, to the Scene collection. To remove it from the scene collection, use :

bpy.context.scene.collection.objects.unlink(obj) 

You can also use :

bpy.data.collections["My Collection"].objects.unlink(obj) 

If you happen to know the collection name.

To iterate over all the collections the object is linked to, use obj.users_collection :

for collection in obj.users_collection:
    collection.objects.unlink(obj)

Note : If you remove an object from all collections in the active scene, the object will disappear from the outliner and you will have to dig into the orphan data or the file data to retrieve it.

Gorgious
  • 30,723
  • 2
  • 44
  • 101