14
$\begingroup$

I have a script that takes in positional data and creates a cube based on their positions. Each time I run the script, I've noticed that the old cubes are still showing up in the User Perspective. It's a pain to go through each cube and manually delete them.

I've googled for a while to find a solution to no avail. I know that

for ob in bpy.data.objects:

Allows me to iterate through the objects in the scene. I get

Camera
Cube
Cube.001
Cube.002
...

but I don't know how to use the API to select only cubes to remove and I don't know how to remove them. Is unlinking the same thing as removing the cubes from the user perspective?

$\endgroup$

1 Answer 1

19
$\begingroup$

This should do the trick, first iterate through everything in your scene, next check if it is as mesh and check if it is a cube (by name using the first 4 chars), then remove it. Also, make sure you are in object mode when running the script.

import bpy

scene = bpy.context.scene

for ob in scene.objects:
    if ob.type == 'MESH' and ob.name.startswith("Cube"):
        ob.select = True
    else: 
        ob.select = False

bpy.ops.object.delete()

Unlinking an object from a scene does not remove it entirely.


Condensed version of the same script thanks to CoDEmanX.

import bpy    
for ob in bpy.context.scene.objects:
    ob.select = ob.type == 'MESH' and ob.name.startswith("Cube")
bpy.ops.object.delete()
$\endgroup$
5
  • 1
    $\begingroup$ ob.name.startswith("Cube") is more efficient self-explaining, and the call to delete() can be moved outside the loop - all selected objects are deleted by a single call. Note that the delete operator will fail if in editmode! Other than that, it's the optimal solution, bpy.data.objects.remove() would cause trouble 'cause of users (scenes and mesh datablocks). $\endgroup$
    – CodeManX
    Commented Apr 21, 2014 at 23:47
  • $\begingroup$ @CoDEmanX Thanks for the hints, need to start practising more "idiomatic blender python" $\endgroup$
    – iKlsR
    Commented Apr 21, 2014 at 23:50
  • $\begingroup$ You're welcome =) Now that I think about it... Shouldn't there be an else clause to deselect all objects that could be selected but don't match the condition? $\endgroup$
    – CodeManX
    Commented Apr 21, 2014 at 23:53
  • 1
    $\begingroup$ @CoDEmanX Another good catch ;), I would have chosen to just deselect everything prior to the loop but that's better. $\endgroup$
    – iKlsR
    Commented Apr 21, 2014 at 23:57
  • $\begingroup$ It could actually be condensed to ob.select = ob.type == 'MESH' and ob.name.startswith("Cube"), although it's a bit less clear in the visual appearance. $\endgroup$
    – CodeManX
    Commented Apr 22, 2014 at 0:02

You must log in to answer this question.

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