Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need a way to detect if animation's clip finished playing and then execute a certain code. Here's some script, that I wrote (called in Update):

    if (Input.GetButtonDown ("Fire1") && pc_atttacking == false && PlayerStats.staminaCurrent != 0) {
        pc_atttacking = true;
        pc_anim.SetBool("attack", true);
    }

    if (pc_anim.GetCurrentAnimatorStateInfo (0).IsName ("attack")) {
        pc_atttacking = false;
        pc_anim.SetBool("attack", false);
    }

But it doesn't work as I want; it executes second code too early - when "attack" animation is at slightly more than half of playing position. I want to execute it when "attack" animation is at last frame.

share|improve this question

You can check if the animation is complete by looking at the normalizedTime property of the Animator's AnimatorStateInfo:

if(pc_anim.GetCurrentAnimatorStateInfo(0).IsName("attack") && 
   pc_anim.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1.0f)
{
    pc_atttacking = false;
    pc_anim.SetBool("attack", false);
}
share|improve this answer

Well, on the other hand sometimes Coroutines would be just like a gift of God for you.

You can use it in more good way.

void Update()
{
    if (Input.GetButtonDown ("Fire1") && pc_atttacking == false && PlayerStats.staminaCurrent != 0) {
        pc_atttacking = true;
        pc_anim.SetBool("attack", true);
        StartCoroutine("OnCompleteAttackAnimation");
    }
}

IEnumerator OnCompleteAttackAnimation()
{
    while(pc_anim.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f)
        yield return null;

    // TODO: Do something when animation did complete
}
share|improve this answer
    
Should work, but this is a bit smelly in my opinion. – Evorlor Feb 29 at 13:58
    
@Evorlor I think it is better than adding more lines in Update – Hamza Hasan Feb 29 at 13:59
    
If you are speaking from a performance point of view, I think it's the same. But not sure...now I'm curious. I do agree though that sticking it in the update method isn't nice either. I guess the smelliness is on Unity's end, unless someone comes up with a clean way to do this. – Evorlor Feb 29 at 14:01
    
+1 for an alternative solution, but I hope others still can think of more. This is something that I have always struggled with in Unity – Evorlor Feb 29 at 14:02
    
I suggest replacing your while loop with: yield return new WaitUntil(() => pc_anim.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f); – Evorlor Feb 29 at 14:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.