5

Using Python to add a keyframe to an object seems easy (see here or here), but how can I add a keyframe to a scene property?

As a concrete example, take bpy.context.scene.gravity.

Garrett
  • 6,596
  • 6
  • 47
  • 75

1 Answers1

10

Even though the examples linked are to keyframe an object, there is in fact no difference and the same methods apply to both.

Simple:

scene = bpy.context.scene
scene.keyframe_insert(data_path="gravity", frame=10.0)

Advanced:

scene = bpy.context.scene
if not scene.animation_data:
    scene.animation_data_create()
if not scene.animation_data.action:
    scene.animation_data.action = bpy.data.actions.new("GravityAction")

fcurve = None
for fcurve in scene.animation_data.action.fcurves:
    if fcurve.data_path == "gravity":
        break
if not fcurve or fcurve.data_path != "gravity":
    fcurve = scene.animation_data.action.fcurves.new("gravity")
keyframe = fcurve.keyframe_points.insert(frame=10.0, value=20.0)
keyframe.interpolation = "LINEAR"
#keyframe.handle_left
#keyframe.handle_right
ideasman42
  • 47,387
  • 10
  • 141
  • 223
pink vertex
  • 9,896
  • 1
  • 25
  • 44