0
$\begingroup$

How would one go about adding animation data (keyframes / FCurves) to an empty object using the Python API?

This is to be able to have full control over creation of keyframes and setting interpolation properties without having to use Object.keyframe_insert, finding the just made keyframe (as the function doesn't return the keyframe), and then adjusting interpolation properties.


Background:

Many posts I've seen about adding animation data via the Python API uses the keyframe_insert function of class bpy_struct, as seen here:

# Add keyframe to x axis on frame 1
obj.location.x = 1.23
obj.keyframe_insert(data_path="location", index=0, frame=1)

This Blender StackExchange answer shows how one can access FCurves of an object once they are created. Though, the post does not show how to create a FCurve from scratch.

To access the FCurve(s) that modifies a data_path on the currently selected object, one can do this (as shown in the post):

import bpy

context = bpy.context
obj = context.object
action = obj.animation_data.action

# All location fcurves on the object
fcurves = [fc for fc in action.fcurves if fc.data_path == "location"]

# Iterate over each axis (of location property)
for fc in fcurves:
    # X axis would be axis == 0
    axis = fc.array_index

Before running the keyframe_insert function on an empty object, the animation_data property of the Object is NoneType. Running keyframe_insert sets this property to an instance of AnimData somehow. animation_data.action therefore is also non-existent, therefore one cannot begin adding FCurves (if even possible).

$\endgroup$
2

Your Answer

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

Browse other questions tagged or ask your own question.