Animation with parameters

Hi all,

So I’m trying to create animation in Unity(it is not imported animation). It’s quite simple animation - I have a cube that I move from (0, 0, 0) to (1,1,1). So I have 2 keyframes. But I want to make my animation use parameters instead of hard coded values.

I found how to make the starting point dynamic and instead of using (0,0,0) it is using the current object position, but I can’t find how to change the end animation position (1,1,1) from code to be (x,y,z). So basically my question is - Is there a way to change keyframe parameters from code(e.g. have animation with dynamic parameters). Note that I’m talking about animation parameters not animator parameters.

Regards Pavel

Not really.

Animations are supposed to be read-only assets that’s created in the editor (or an external program), and played back in real time. There are ways to edit the keyframes of an animation asset in scripting, but that’s editor time scripts, and it won’t work during gameplay.

What you want to do, though, is easy. The AnimationCurve class is freely available to use in scripts. If you have it as a public field on a MonoBehaviour, you can edit it through the inspector. You can also create AnimationCurves, add keyframes to them, and evaluate the curve completely from code.

The best way to do what you’re trying to do is probably to use a public AnimationCurve, and interpret it’s values as percentage towards the goal. A very easy example would be:

public AnimationCurve moveCurve;
public Vector3 target;

private Vector3 startPoint;

void Awake() {
    startPoint = transform.position;

void Update() {
    transform.position = Vector3.Lerp(startPoint, target, moveCurve.Evaluate(Time.time));