Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

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:
    415
    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.