Add Keyframe Via Script/Hotkey

I’m using the new Timeline feature and one of the things I’ve noticed is that the only method for keying something is autokey – there’s no ‘add keyframe’ button or command anywhere. I’ve scraped the documentation for it, and also for animation clips in general and can’t find any command or script that allows me to add a keyframe to a Unity animation via code.

Does anyone know how this could be done, or have any resources that could help?

Hi,

I’m having the same issue as you do. I basically want to start from a timeline created procedurally by adding keyframes, then tweak it manually and be able to scrub the animation.

I think what you’re looking for is SetCurve.

You have to access the TrackAsset object instance, then get the clips with GetClips.

Following that, you’d need to access the animationClip referred by the TimelineClip with animationClip.

When accessing the animation clip, you can set its curve by calling SetCurve and pass it a curve created with the number of keyframes you [want] (Unity - Scripting API: AnimationCurve.AnimationCurve).

So in the end we have:
foreach(var timelineClip in TimelineAsset.GetRootTrack().GetClips()) { var myCurve = new AnimationCurve(); myCurve.AddKey(0.1f, 1.0f); timelineClip.animationClip.SetCurve("", typeof(Transform), "localPosition.x", curve); }

Or you can use AnimationUtility.GetCurveBindings to get the curve bound with the property you want and add key frames to it.