Search Unity

How to Start Animation from x Frame?

Discussion in 'Animation' started by davidhfw, Oct 9, 2019.

  1. davidhfw

    davidhfw

    Joined:
    Aug 17, 2016
    Posts:
    77
    I have a series of sprites in the animation and I would like to start the animation from the 7th frame in the series or 2 sec (later) from the start of the animation.

    Is that possible in code or the editor?

    Thanks!
     
  2. Kybernetik

    Kybernetik

    Joined:
    Jan 3, 2013
    Posts:
    541
    If you are using an Animator Controller, you can't really do it cleanly. The Animator.Play method can take a normalized time parameter, but you have no way of accessing the length of the animation until it is already playing and you can't access its frame rate at all so you would need to either hard code those details or serialize them separately.

    But if you use Animancer (link in my signature) you can control the time of animations using a script as shown here or if you use a ClipState.Serializable you can optionally set a custom Start Time in the Inspector.
     
  3. davidhfw

    davidhfw

    Joined:
    Aug 17, 2016
    Posts:
    77
    Thank you Kybernetik.

    I should have articulated the context of my original post. My bad, here goes:

    I have an 'explosion' animator attached to an asteroid game object. When a projectile hits the asteriod, it will play the explosion animation and destroy the asteriod game object. What I wanted to achieve is to have the explosion animation in sync with the disappearance of the asteroid.

    However, the asteroid always disappears before the animation plays, even when I put in a delay in the Destroy method.

    Code (csharp):
    1.  
    2. explosionAnimator.SetTrigger("onAsteroidDestroy"); // #1
    3. GameObject.Destroy(gameObject, 5.0f);
    4.  
    The delay argument (5.0f) in the Destroy method works as expected if I comment out #1.
    Any reason for this behavior? Thanks!
     
  4. Kybernetik

    Kybernetik

    Joined:
    Jan 3, 2013
    Posts:
    541
    Having a delayed Destroy command shouldn't change anything about animations during that delay so I have no idea what could be wrong with that.

    What exactly do you mean by "have the explosion animation in sync with the disappearance of the asteroid"?

    If you want to destroy the asteroid exactly at the end of the explosion animation, that's another thing Animancer makes easy:

    Code (CSharp):
    1. AnimationClip clip;
    2. AnimancerComponent explosionAnimancer;
    3.  
    4. var state = explosionAnimancer.Play(clip);
    5. state.OnEnd = () =>
    6. {
    7.     Destroy(gameObject);
    8. };
    9.  
    10. // Or since you aren't going to be fiddling with the speed of an explosion or anything:
    11.  
    12. explosionAnimancer.Play(clip);
    13. Destroy(gameObject, clip.length);
    If you want the asteroid to be destroyed at some other point during the animation, you should look into Animation Events.