Home > Blockchain >  Play animation 5 times
Play animation 5 times

Time:06-02

I am trying to play my animator's animation 5 times. That is after every animation that ends, it has to replay it for another time. How do I do this?

public Animator anim;

void Start ()
       {
             StartCoroutine(PlayAnimInterval(5));
       }

      private IEnumerator PlayAnimInterval(int n)
      {
          while (n > 0)
          {
              anim.Play("wave", -1, 0F);
              --n;
              //yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length); //Returns 1 which is wrong
          }
      }

CodePudding user response:

Use the for loop in IEnumerator to solve the problem. Also make sure you enter the layer number correctly. Here the wave state is repeated 5 times in layer zero.

private IEnumerator PlayAnimInterval(int n)
{
    for (int i = 0; i < n; i  )
    {
        anim.Play("wave", 0, 1);
        yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length);
    }
}

How to detect Animator Layer?

The animator layer is an array. By adding each layer in the layers section, its index is also added. You can find its code below.

enter image description here


Repeat State Info with Behaviour

In this method you can solve the problem of repetition in any state. Just create a behavior like the one below and just add the number of repetitions. This method also works independently of the layer.

enter image description here

enter image description here

public class Repeat : StateMachineBehaviour
{
    public int repeatTime;
    public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (repeatTime <= 0) return;
        
        repeatTime--;
        animator.Play(stateInfo.fullPathHash);
    }
} 
  • Related