0
$\begingroup$

Before 4.0, it was possible to use context override with operators. It was very handy to be able to delete a list of objects without messing with the current selection.

objs = [bpy.context.scene.objects['my_obj_01'], bpy.context.scene.objects['my_obj_02']]
bpy.ops.object.delete({"selected_objects": objs})

This got removed in 4.0: https://projects.blender.org/blender/blender/commit/ac263a9bce53e190d07d679a058a230e91e722be It now returns an error: ValueError: 1-2 args execution context is supported

What is the best way to do the same thing now? This is my pretty long workaround:

# Objects to delete
objs = [bpy.context.scene.objects['my_obj_01'], bpy.context.scene.objects['my_obj_02']]
#Store the current object selection
current_sel = context.selected_objects
active_obj = context.view_layer.objects.active

# Check if objects to delete are currently selected and remove them or it will fail at restoring selection.
for o in objs:
    if active_obj == o:
        active_obj = None
    if o in current_sel:
        current_sel.remove(o)
        
# Select objects to delete
bpy.ops.object.select_all(action='DESELECT')
for o in objs:
    bpy.data.objects[o].select_set(True)

bpy.ops.object.delete()

#Restore the previous selection
if current_sel:
    for o in current_sel:
        bpy.data.objects[o.name].select_set(True)
if active_obj:
    context.view_layer.objects.active = active_obj
$\endgroup$
2
  • $\begingroup$ context can still be overriden, but now you have to use the context manager with bpy.context.temp_override(...) $\endgroup$ Commented Oct 8, 2023 at 23:01
  • $\begingroup$ I did not get it to work. I have tried different syntaxes but it does not delete my objects. Could you share a working example please? $\endgroup$
    – chafouin
    Commented Oct 8, 2023 at 23:25

1 Answer 1

3
$\begingroup$
import bpy


objs = [
    bpy.data.objects['Cube'],
    bpy.data.objects['Cube.001']
]


for obj in objs:
    bpy.data.objects.remove(obj)
$\endgroup$
3
  • $\begingroup$ Remove does not delete associated data, unlike the delete operator. So for each object, we need to search for associated data and its type, and remove that data, which is also cumbersome? $\endgroup$
    – chafouin
    Commented Oct 9, 2023 at 11:34
  • 2
    $\begingroup$ The delete operator doesn't delete data either ? Note you can also use bpy.data.batch_remove(objs) (faster if you have a lot of objects to delete, it doesn't trigger a redraw each time) $\endgroup$
    – Gorgious
    Commented Oct 9, 2023 at 12:16
  • $\begingroup$ I thought it did, according to what I was able to find on the net. But thanks for the batch_remove, I'll give it a try. $\endgroup$
    – chafouin
    Commented Oct 9, 2023 at 14:19

You must log in to answer this question.

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