10
$\begingroup$

I was looking after some information about armature and bones, so I can continue my importer script. I found some nice info here; no BMesh, and simple enough for my needs as beginner, so just perfect. But while looking at the code I saw that it uses "edit mode" (line 120), what I wanted to avoid.

So my question is: can I programmatically add/manipulate bones, without edit mode? Is there any better way then in this code?

I also tried to use the "bones" collection, but I could not append/new/add items into them.

$\endgroup$
2
  • 1
    $\begingroup$ Learn more about armature by reading Rigify addon scripts. I recommend init.py and generate.py for starter. Also, as @Adhi mentioned, you must be in edit mode to add or remove bones. $\endgroup$
    – Ali Jibran
    Commented Aug 16, 2013 at 20:45
  • 1
    $\begingroup$ I have to say the "edit mode" requirement annoys me. I have a philosophy that all operations should be possible in python without using anything from bpy.ops or fiddling with the editor state. In practice, developers have limited time and some operations are just unreasonable (like unlinking an object from the scene while the user is in edit mode). Still, I think those principles are a good goal. $\endgroup$
    – Mutant Bob
    Commented Mar 28, 2014 at 21:18

1 Answer 1

10
$\begingroup$

No, The armature must be in Edit mode for us to be allowed to add or remove bones. We can switch into and out of it, using bpy.ops.object.mode_set. An idiom I use a couple of times in my addon, is to store initial mode in a variable (prev_mode), then restore it when I'm finished:

prev_mode = armature.mode # save

bpy.ops.object.mode_set(mode='EDIT')
for bone in context.selected_bones:
    # do anything in edit mode
    hook_name = PRF_HOOK + bone.name
    hook = armature.data.edit_bones.new(hook_name)

bpy.ops.object.mode_set(mode='POSE')
for bone in context.selected_pose_bones:
    # do anything in pose mode
    hook = armature.pose.bones[PRF_HOOK + bone_name]
    ct_constraint = hook.constraints.new('COPY_TRANSFORMS')

bpy.ops.object.mode_set(mode=prev_mode) # restore

This way, we can access any editing mode, any number of times, without the user even notice when the script is finished.

$\endgroup$
1
  • $\begingroup$ This snippet: wiki.blender.org/index.php/Dev:Py/Scripts/Cookbook/… seems to favour bpy.ops.object.editmode_toggle(). Maybe it's something new, or maybe it's not a good idea in case it's already edit mode? In any case I haven't tested it. $\endgroup$
    – Vegard
    Commented Jun 19, 2016 at 7:17

You must log in to answer this question.

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