Skip to content

Instantly share code, notes, and snippets.

@yanniboi
Created May 18, 2021 09:38
Show Gist options
  • Save yanniboi/41f4dcf492c0b2c32e2a90cd5d0cd785 to your computer and use it in GitHub Desktop.
Save yanniboi/41f4dcf492c0b2c32e2a90cd5d0cd785 to your computer and use it in GitHub Desktop.
Reverse a keyframe animation in Unity

Original solution can be found here: http://answers.unity.com/answers/477764/view.html

This is an editor script to reverse an AnimationClip. Since it's an editor script you have to put it in a folder called "Editor". Once it's there a new mainmenu item called "Tools" will appear (if not just click the "File" menu once).

How to use:

Now you have to duplicate the AnimationClip in Unity by pressing CTRL+D while you have selected the AnimationClip. Select the duplicated Clip and click on Tools/ReverseAnimation. This will reverse the animation. Now you can add this new animation to your Animation Controller.

using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class ReverseAnimation : Editor
{
public static AnimationClip GetSelectedClip()
{
var clips = Selection.GetFiltered(typeof(AnimationClip),SelectionMode.Assets);
if (clips.Length > 0)
{
return clips[0] as AnimationClip;
}
return null;
}
[MenuItem("Tools/ReverseAnimation")]
public static void Reverse()
{
var clip = GetSelectedClip();
if (clip == null)
return;
float clipLength = clip.length;
List<AnimationCurve> curves = new List<AnimationCurve>();
EditorCurveBinding[] editorCurveBindings = AnimationUtility.GetCurveBindings(clip);
foreach (EditorCurveBinding i in editorCurveBindings)
{
var curve = AnimationUtility.GetEditorCurve(clip, i);
curves.Add(curve);
}
clip.ClearCurves();
for (int i = 0; i < curves.Count; i++)
{
var curve = curves[i];
var binding = editorCurveBindings[i];
var keys = curve.keys;
int keyCount = keys.Length;
var postWrapmode = curve.postWrapMode;
curve.postWrapMode = curve.preWrapMode;
curve.preWrapMode = postWrapmode;
for (int j = 0; j < keyCount; j++ )
{
Keyframe K = keys[j];
K.time = clipLength - K.time;
var tmp = -K.inTangent;
K.inTangent = -K.outTangent;
K.outTangent = tmp;
keys[j] = K;
}
curve.keys = keys;
clip.SetCurve(binding.path, binding.type, binding.propertyName, curve);
}
var events = AnimationUtility.GetAnimationEvents(clip);
if (events.Length > 0)
{
for (int i = 0; i < events.Length; i++)
{
events[i].time = clipLength - events[i].time;
}
AnimationUtility.SetAnimationEvents(clip,events);
}
Debug.Log("Animation reversed!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment