How to Select an Object in Blender using the API

selection in Blender

I’d wanted to select a certain mesh object and then edit it, but was getting weird errors, like:

RuntimeError: Operator bpy.ops.mesh.select_all.poll() failed, context is incorrect

and

RuntimeError: Operator bpy.ops.object.mode_set(mode='EDIT').poll() failed, context is incorrect

I couldn’t find my actual initial code, so here’s me trying to replicate it. All I’m doing is selecting the first cube.

my_object = bpy.context.scene.objects['Cube']
my_object.select = True
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')

>>> RuntimeError: Operator bpy.ops.mesh.select_all.poll() failed, context is incorrect

Turns out I needed to set the object as the active object and deselect any other object. If the originally selected object was in EDIT mode, I needed to toggle to OBJECT mode before toggling back EDIT mode. Otherwise, bpy.ops.object.mode_set(mode='EDIT') will appear finished but actually fail.

other_object = bpy.context.scene.objects['Cube.002']
other_object.select = False

my_object = bpy.context.scene.objects['Cube']
my_object.select = True
bpy.context.scene.objects.active = my_object

bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')

bpy.ops.mesh.select_all(action='SELECT')
success

Success!

Hope this helps!

*My example snippet can replicate the select_all error, if the original object was in EDIT mode, but I can’t seem to reproduce the edit_mode error. However, I haven’t had any problems after deselecting all other objects and toggling to OBJECT mode before any further operations.

Blender 2.72

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: