I find the bpy.ops, but not find the low level python way to get obj inside a collection and delete . Any idea?
1 Answer
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=True
is the default, and hence can be left out, will unlink from the collection, and all others containing this object, for you.
-
$\begingroup$ Nice explanation, in my case I solved with : while mycol.objects: ... mycol.objects.unlink(mycol.objects[0]) $\endgroup$– Noob CatCommented Mar 2, 2019 at 4:43