2
$\begingroup$

In blender, I wanted to add multiple armature bones to a set of empties in my scene. In order to do this, I found this script:

for empt in bpy.data.objects:
    if empt.type=='EMPTY':
        bpy.context.view_layer.objects.active=empt
        bpy.ops.object.armature_add(enter_editmode=False, align='WORLD', 
        location=empt.matrix_world.translation, scale=(1, 1, 1))

With this, separate armatures are being added , which I can join to a single one later, that is not the problem.

Now, While adding these armatures, I would like to give a name of my choice to the bones(of the armature). How do I do that through the python API, while I add armature. The bpy.ops.object.armature_add function doesn't have a "bone name", attribute, nor does it return the instance of armature that got created, so that i could then access its bone and rename?

Please advise. Any help would be appreciated. Thanks

$\endgroup$

1 Answer 1

2
$\begingroup$

Since bpy.ops adds the armature to the end of bpy.data.armatures you can get the armature immediately after the call to armature_add as bpy.data.armatures[-1]. Once you've done that you could pass the armature to a separate function to process it. That changes your loop to

for empt in bpy.data.objects:
    if empt.type=='EMPTY':
        bpy.context.view_layer.objects.active=empt
        bpy.ops.object.armature_add(enter_editmode=False, align='WORLD', 
        location=empt.matrix_world.translation, scale=(1, 1, 1))
        do_rename(bpy.data.armatures[-1])

Since you only have one bone in your armature you can rename it using a very trivail version of do_rename:

def do_rename(anArmature):
    anArmature.bones[0].name = "newname"

This means, of course you could combine it all into a single line of code appended to your original loop:

import bpy
for empt in bpy.data.objects:
    if empt.type=='EMPTY':
        bpy.context.view_layer.objects.active=empt
        bpy.ops.object.armature_add(enter_editmode=False, align='WORLD', 
        location=empt.matrix_world.translation, scale=(1, 1, 1))
        bpy.data.armatures[-1].bones[0].name = "new name"

but if you want to do something more complex than define a single bone's name, I would recommend the function.

$\endgroup$
1
  • $\begingroup$ bpy.data.armatures[-1] seems to give the last armature alphabetically by name. not the last added armature. $\endgroup$ Commented Sep 21, 2023 at 16:38

You must log in to answer this question.

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