2
$\begingroup$

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)
$\endgroup$
4
  • 2
    $\begingroup$ An object can be linked to multiple collections by design. $\endgroup$ Commented Jan 20, 2020 at 19:44
  • 1
    $\begingroup$ You'll have to unlink it from its old collection. $\endgroup$ Commented Jan 20, 2020 at 19:50
  • $\begingroup$ i tried doing that... bpy.context.scene.collection.children.unlink(myObj) TypeError: CollectionChildren.unlink(): error with argument 1, "child" - Function.child expected a Collection type, not set $\endgroup$ Commented Jan 20, 2020 at 19:58
  • 2
    $\begingroup$ Got it... bpy.context.scene.collection.objects.unlink(myObj) $\endgroup$ Commented Jan 20, 2020 at 20:05

1 Answer 1

3
$\begingroup$

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.

$\endgroup$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.