9
$\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$
  • 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 Aug 16 '13 at 20:45
  • $\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 Mar 28 '14 at 21:18
9
$\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.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.