Search Unity

Why is my animation jumping to the last keyframe when set in script?

Discussion in 'Animation' started by cinnamonrollapplecider, Jul 14, 2022.

  1. cinnamonrollapplecider

    cinnamonrollapplecider

    Joined:
    Jul 6, 2017
    Posts:
    9
    I am trying to rotate a gameObject by scripting it. This gameObject is a bone added in SkinningEditor, which should not make a difference. The script I wrote below is attached to the bone.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class DeformBone : MonoBehaviour
    5. {
    6.      void LateUpdate()
    7.      {
    8.          setAllCurves();
    9.      }
    10.      private void setAllCurves()
    11.      {
    12.          var angle = Quaternion.Euler(0, 0, 5);
    13.          var rotXcurve = AnimationCurve.EaseInOut(0, 0, 5, angle.x);
    14.          var rotYcurve = AnimationCurve.EaseInOut(0, 0, 5, angle.y);
    15.          var rotZcurve = AnimationCurve.EaseInOut(0, 0, 5, angle.z);
    16.          var rotWcurve = AnimationCurve.EaseInOut(0, 0, 5, angle.w);
    17.          // set the curve here
    18.          AnimationClip clip = new AnimationClip();
    19.          clip.legacy = true;
    20.          clip.SetCurve("", typeof(Transform), "localRotation.x", rotXcurve);
    21.          clip.SetCurve("", typeof(Transform), "localRotation.y", rotYcurve);
    22.          clip.SetCurve("", typeof(Transform), "localRotation.z", rotZcurve);
    23.          clip.SetCurve("", typeof(Transform), "localRotation.w", rotWcurve);
    24.          // play the curve here
    25.          if (gameObject.GetComponent<Animation>() == null)
    26.          {
    27.              // add the component
    28.              var animation = gameObject.AddComponent<Animation>();
    29.              animation.playAutomatically = false;
    30.              animation.wrapMode = WrapMode.PingPong;
    31.            
    32.          }
    33.          GetComponent<Animation>().AddClip(clip, "rotateyo");
    34.          GetComponent<Animation>().Play("rotateyo");
    35.      }
    36. }
    However, the animation jitters quickly back and forth, jumping from keyframe to keyframe and then it gets faster and faster until it just looks a bit crazy. I want it to rotate at the angle indicated slowly. I have tried putting this in Start() - this only jumps it to the last keyframe where it stays, and FixedUpdate/Update where the same thing happens.

    I can see in the Inspector that I have successfully added an Animation to the bone and that the curves are being set up properly. What am I doing wrong?