Search Unity

Sampling animation clip

Discussion in 'Scripting' started by MiaoBolverk, Oct 25, 2018.

  1. MiaoBolverk

    MiaoBolverk

    Joined:
    Feb 6, 2018
    Posts:
    26
    Out of necessity, I need to set the animation type on a specific mesh to Legacy.

    Here is some example code:
    Code (csharp):
    1.     private const float FramesPerSecond = 50f;
    2.     private float numFramesElapsed;
    3.     private float numTotalFramesInMovementClip;
    4.  
    5.     public GameObject AnimatedMesh;
    6.     public AnimationClip MovementClip;
    7.  
    8.     private void Awake()
    9.     {
    10.        this.numTotalFramesInMovementClip = this.MovementClip.length * FramesPerSecond;
    11.     }
    12.  
    13.     private void Update()
    14.     {
    15.        if (this.numFramesElapsed <= this.numTotalFramesInMovementClip)
    16.        {
    17.            this.MovementClip.SampleAnimation(this.AnimatedMesh, this.numFramesElapsed / this.numTotalFramesInMovementClip * this.MovementClip.length);
    18.            this.numFramesElapsed++;
    19.        }
    20.     }
    When I start the game, the animation clip also begins playing, just as expected. However, once this.numFramesElapsed becomes strictly greater than this.numTotalFramesInMovementClip -- i.e., once we no longer enter the if clause at all -- the mesh immediately returns to its position as specified at the very beginning of the clip, and just stays there. This violated my expectations -- I'd expected the mesh to remain in the position specified at the end of the clip.

    Do I really have to run this.MovementClip.SampleAnimation(this.AnimatedMesh, this.MovementClip.length); in every single Update() call after exiting the if clause? Is there any other way to ensure that the mesh stays in the final position specified by the clip?