Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question Animation playback from code does not work correctly.

Discussion in 'Animation' started by Zimaell, Feb 22, 2023.

  1. Zimaell

    Zimaell

    Joined:
    May 7, 2020
    Posts:
    435
    I want to play the animation from the code, for baking frame by frame, but I noticed that it does not work as it should.
    I made a simple example from the documentation.
    Code (CSharp):
    1. using UnityEngine;
    2. public class test : MonoBehaviour{
    3.     private Animator CharacterAnimator;
    4.     public AnimationClip clip;
    5.     private void Start(){
    6.         CharacterAnimator =  GetComponent<Animator>();
    7.         }
    8.     private void Update(){
    9.         clip.SampleAnimation(CharacterAnimator.gameObject, clip.length - Time.time);
    10.         }
    11.     }
    but it doesn't work correctly, namely - one cycle is played back and stops (backwards), then on the spot it varies by Y + -0.1, any predefined transformation is reset to 0
    (if you run the animation directly in the animator itself, then everything works correctly)

    Tell me what's wrong?
     
  2. donotprikel

    donotprikel

    Joined:
    Nov 14, 2022
    Posts:
    26
    If your goal is to play the animation from the code so that you can bake it frame by frame, you may want to try using the Play() method on the Animator component instead of the SampleAnimation() method.


    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Test : MonoBehaviour {
    4.     private Animator characterAnimator;
    5.     public AnimationClip clip;
    6.  
    7.     private void Start() {
    8.         characterAnimator = GetComponent<Animator>();
    9.         characterAnimator.playbackTime = 0;
    10.         characterAnimator.speed = 0;
    11.     }
    12.  
    13.     private void Update() {
    14.         if (characterAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1) {
    15.             characterAnimator.playbackTime = 0;
    16.             characterAnimator.speed = 0;
    17.             return;
    18.         }
    19.  
    20.         characterAnimator.speed = 0;
    21.         characterAnimator.Play(clip.name, 0, characterAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime);
    22.     }
    23. }
    24.  
     
    Zimaell likes this.