1
$\begingroup$

I'm running a script to create a bone and rotate it by setting rotation_euler of the PoseBone. But I got wrong results from the scripts. My scripts code:

import bpy 
bpy.ops.object.armature_add()
bpy.ops.object.editmode_toggle()
bpy.context.object.data.edit_bones[0].name = 'Bone_1'
bpy.ops.object.mode_set(mode='POSE')
b = bpy.context.object.pose.bones['Bone_1']
b.rotation_mode = 'XYZ'
aaa = b.y_axis
b.rotation_euler[0] = 1.57
b.rotation_euler[1] = 0
b.rotation_euler[2] = 0
bbb = b.y_axis
print(aaa, bbb)

scripts running result:

<Vector (0.0000, 0.0000, 1.0000)> <Vector (0.0000, 0.0000, 1.0000)>

The bone model is rotated correctly, however the outputs are wrong because the attribute of the bone has not changed.
But when I using the python console to run the same code line by line.
The outputs are correct:

>>> bpy.ops.object.armature_add()
{'FINISHED'}

>>> bpy.ops.object.editmode_toggle()
{'FINISHED'}

>>> bpy.context.object.data.edit_bones[0].name = 'Bone_1'
>>> bpy.ops.object.mode_set(mode='POSE')
{'FINISHED'}

>>> b = bpy.context.object.pose.bones['Bone_1']
>>> b.rotation_mode = 'XYZ'
>>> aaa = b.y_axis
>>> b.rotation_euler[0] = 1.57
>>> b.rotation_euler[1] = 0
>>> b.rotation_euler[2] = 0
>>> bbb = b.y_axis
>>> print(aaa, bbb)
<Vector (0.0000, 0.0000, 1.0000)> <Vector (0.0000, -1.0000, 0.0008)>

The bone's attribute has changed correctly.
I don't understand why the console runs correctly but the script runs incorrectly.
Any suggestion where I'm going wrong?

$\endgroup$

1 Answer 1

2
$\begingroup$

In the python console, the scene is updated at each step, this is not the case in the script.

You can add bpy.context.view_layer.update() after the rotation is changed.

import bpy 
bpy.ops.object.armature_add()
bpy.ops.object.editmode_toggle()
bpy.context.object.data.edit_bones[0].name = 'Bone_1'
bpy.ops.object.mode_set(mode='POSE')
b = bpy.context.object.pose.bones['Bone_1']
b.rotation_mode = 'XYZ'
aaa = b.y_axis
b.rotation_euler[0] = 1.57
b.rotation_euler[1] = 0
b.rotation_euler[2] = 0
bpy.context.view_layer.update() # Update here
bbb = b.y_axis
print(aaa, bbb)
$\endgroup$
1
  • $\begingroup$ Thanks! It's done $\endgroup$
    – Nutcracker
    Commented Jan 30, 2023 at 8:29

You must log in to answer this question.

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