Check if animation clip has finished

2020-02-15 06:28发布

问题:

This is the simple code inside of update. sadly it is not working for me. Even I have set Wrap Mode to clamp Forever.

 if (trainGO.GetComponent<Animation>()["Start"].time >= trainGO.GetComponent<Animation>()["Start"].length)
 {
      blackTrain.SetActive(true);
      redTrain.SetActive(false);
 }

How can I check that animation clip have finished so that I can do some work? I don't want to use WaitForSeconds method, because I am working on Time and each time a new animation will be played,

回答1:

Basically like this ...

PlayAnimation(); // Whatever you are calling or using for animation
StartCoroutine(WaitForAnimation(animation));

private IEnumerator WaitForAnimation ( Animation animation )
    {
    while(animation.isPlaying)
        yield return null;

    // at this point, the animation has completed
    // so at this point, do whatever you wish...
    Debug.Log("Animation completed");
    }

You can trivially google thousands of QA about this example, http://answers.unity3d.com/answers/37440/view.html

If you do not fully understand coroutines in Unity, step back and review any of the some 8,000 full beginner tutorials and QA regarding "coroutines in Unity" on the web.

This is really the way to check an animation is finished in Unity - it's a standard technique and there's really no alternative.

You mention you want to do something in Update() ... you could possibly do something like this:

private Animation trainGoAnime=ation;

public void Update()
    {

    if ( trainGoAnimation.isPlaying() )
        {
        Debug.Log("~ the animation is still playing");
        return;
        }
    else
        {
        Debug.Log("~ not playing, proceed normally...");
        }
    }

I strongly encourage you to just do it with a coroutine; you'll end up "in knots" if you try to "always use Update". Hope it helps.


FYI you also mention "actually the scenario is: at specified time (Time/clock separately running). I have to play an animation thats why i am using update to check the time and run animation accordingly"

This is very easy to do, say you want to run the animation 3.721 seconds from now...

private float whenToRunAnimation = 3.721;

it's this easy!

    // run horse anime, with pre- and post- code
    Invoke( "StartHorseAnimation", whenToRunAnimation )

private void StartHorseAnimation()
  {
  Debug.Log("starting horse animation coroutine...");
  StartCoroutine(_horseAnimationStuff());
  }

private IENumerator _horseAnimationStuff()
  {
  horseA.Play();
  Debug.Log("HORSE ANIME BEGINS");
  while(horseA.isPlaying)yield return null;
  Debug.Log("HORSE ANIME ENDS");
  ... do other code here when horse anime ends ...
  ... do other code here when horse anime ends ...
  ... do other code here when horse anime ends ...
  }