如何知道动画剪辑已完成



所以有两种方法[我通过搜索得到的。如果有其他方法,请分享]。

  • isPlaying属性(示例1)
  • 动画时间(示例2)

两者我都不想使用,因为第一种方法是使用我不想使用的Co例程第二种是使用时间,如果增加动画速度,则时间将无法正常工作,从而影响代码。

示例1

   public class AnimationSequancePlayer : MonoBehaviour {

    public Animation animation; // The animation we want to play the clips in.
    public AnimationClip[] animationClips; // The animation clips we want to play in order.
    int _currentClipOffset;
    void Start()
    {
        foreach (AnimationClip clip in animationClips)
        {
            animation.AddClip(clip, clip.name); // Make sure the animation player contains all of our clips.
        }
        PlaySequence();
    }
    public void PlaySequence()
    {
        _currentClipOffset = 0; // Reset the index to start at the beginning.
        PlayNextClip();
    }
    public void StopSequence()
    {
        animation.Stop();
        StopAllCoroutines();
    }
    void PlayNextClip()
    {
        animation.Play(animationClips[_currentClipOffset].name); // Play the wanted clip
        if (_currentClipOffset != animationClips.Length)
        { // Check if it's the last animation or not.
            StartCoroutine(WaitForAnimationEnd(() => PlayNextClip())); // Listen for end of the animation to call this function again.
            _currentClipOffset++; // Increase index for next time;
        }
    }
    IEnumerator WaitForAnimationEnd(Action onFinish)
    {
        while (animation.isPlaying)
        { // Check if the animation is playing or not
            yield return null;
        }
        if (onFinish != null) { onFinish(); } // Call the function give in parameter.
    }
}

示例2

 if (GetComponent<Animation>()["Move Crane"].time >= 3f)
        {
         ///logic after animation reached at specified time specified time
        }

这个简短的代码片段使我能够做到这一点。注释中也给出了代码说明。对未来的用户有帮助。

bool animationClipPlaying = false;
void Update()
{
     if (GetComponent<Animation>().IsPlaying(clipNameCompare))
     {
         //as animation start to play true the bool
         animationClipPlaying = true; //true this for comparsion
     }
     //if animation is not playing and the bool is true then, animation finished
     else if (!GetComponent<Animation>().IsPlaying(clipNameCompare) && animationClipPlaying)
     {
         Debug.Log(clipNameCompare : " has finished");
         //False so that this condition run only once
         aanimationClipPlaying = false; 
     }
}

最新更新