Unity3D:Animator动画播放完成事件

上一篇文章说了音频播放完成事件的方法,这篇文章我就来说说Animator动画的播放完成事件。其原理和AudioSource的原理是一样的,只是稍微有一点区别就是Animator的动画可能不止一个动画片段,所以在播放动画的时候要有一个判定是哪一个片段。下面是代码。

using System.Collections;
using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(Animator))]
public class AnimatorManager : MonoBehaviour
{
    public static AnimatorManager _Instence;
    public static AnimatorManager Instance
    {
        get
        {
            if (_Instence == null)
            {
                GameObject AnimatorManager = new GameObject("AnimatorManager");
                _Instence = AnimatorManager.AddComponent<AnimatorManager>();
            }
            return _Instence;
        }
    }
    public void PlayAnimator(Animator _animator, string stateName, UnityAction callback, float normalizedTime)
    {
        PlayAnimator(_animator, stateName, callback, -1, normalizedTime);
    }
    public void PlayAnimator(Animator _animator, string stateName, UnityAction callback, int layer)
    {
        PlayAnimator(_animator, stateName, callback, layer, 0);
    }
    public void PlayAnimator(Animator _animator, string stateName, UnityAction callback, int layer = -1, float normalizedTime = 0)
    {
        AnimationClip[] AnimationClips = _animator.runtimeAnimatorController.animationClips;
        float _time = 0;
        for (int i = 0; i < AnimationClips.Length; i++)
        {
            if (AnimationClips[i].name == stateName)
            {
                _time = AnimationClips[i].length;
            }
        }
        _animator.Play(stateName, layer, normalizedTime);
        StartCoroutine(AnimatorPlayFinished(_time, callback));
    }
    private IEnumerator AnimatorPlayFinished(float time, UnityAction callback)
    {
        yield return new WaitForSeconds(time);
        callback.Invoke();
    }
}

在代码里还有一些重载的方法,是因为播放动画的时候可能会有层级和从哪一帧开始播放的需求,所以就写了重载方法,方便去调用。使用方法在这里就不说了,有什么不明白的可以直接找我。知无不言言无不尽。

You May Also Like

About the Author: 大腿Plus

发表评论