0
$\begingroup$

I find the bpy.ops, but not find the low level python way to get obj inside a collection and delete . Any idea?

$\endgroup$

1 Answer 1

2
$\begingroup$

Unlink an object to remove it from a collection.

Py console code, for example sake, creates a new collection that is a copy of "Collection 1". It contains the default file objects "Cube" "Camera" and "Lamp", and like the original is a child of scene collection.

>>> mycol = D.collections['Collection 1'].copy()
>>> mycol.name
'Collection 1.002'

>>> mycol.objects[:]
[bpy.data.objects['Cube'], bpy.data.objects['Lamp'], bpy.data.objects['Camera']]

To get by name and remove the "Cube" object from collection. (If there is no object named "Cube" in collection get returns None)

>>> cube = mycol.objects.get("Cube")
>>> # remove it from collection
>>> mycol.objects.unlink(cube)
>>> mycol.objects[:]
[bpy.data.objects['Lamp'], bpy.data.objects['Camera']]

Loop thru and empty the whole collection. Note mycol.objects is boolean False when emtpy.

>>> while mycol.objects:
...     mycol.objects.unlink(mycol.objects[0])
...     
>>> mycol.objects[:]
[]

To remove the object ob from file use bpy.data.objects.remove(ob, do_unlink=True) Unlinking do_unlink=Trueis the default, and hence can be left out, will unlink from the collection, and all others containing this object, for you.

$\endgroup$
1
  • $\begingroup$ Nice explanation, in my case I solved with : while mycol.objects: ... mycol.objects.unlink(mycol.objects[0]) $\endgroup$
    – Noob Cat
    Commented Mar 2, 2019 at 4:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .