栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

Unity Animation动画结束回调

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity Animation动画结束回调

最近在做虚拟仿真的项目,因为要大量用到Animation动画。又不可能给每一个动画都增加一个evnt事件就写了一个工具动态添加事件(事件动态添加并不会添加到控制器上)

代码片段一

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.Events;
public static class AnimationDetection
{
    public static Animation CurrPlayAnim;//当前播放动画
    private static UnityAction CallBack;//当前动画播放结束回调

    public static bool isPlay
    {
        get
        {
            if (CurrPlayAnim != null)
                return CurrPlayAnim.isPlaying;
            else
                return false;
        }
    }

    public static void Play(this Animation animation, string animName = null, UnityAction callBack = null)
    {

        CurrPlayAnim = animation;
        CallBack = callBack;

        if (CallBack != null)
        {
            if (CurrPlayAnim.gameObject.GetComponent() == null)
                CurrPlayAnim.gameObject.AddComponent().CallBack = callBack;

            AnimationClip clips = null;
            clips = CurrPlayAnim.GetClip(animName);
            //创建新事件
            AnimationEvent m_animator = new AnimationEvent();
            //对应事件触发相应函数的名称
            m_animator.functionName = "MyCallBack";
            //设定对应事件在相应动画上的触发时间点
            m_animator.time = CurrPlayAnim[animName].length;
            clips.AddEvent(m_animator);

            CurrPlayAnim.Rewind();
        }

        if (animName == null)
            CurrPlayAnim.Play();
        else
            CurrPlayAnim.Play(animName);

    }

}

 

代码片段二

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class AnimCallBack : MonoBehaviour
{
    public UnityAction CallBack;
    public void MyCallBack() => CallBack?.Invoke();
}

代码片段二的主要作用就是函数映射,在代码片段一中这么一行绑定了事件m_animator.functionName = "MyCallBack";

 

对应不同场景可能还需要更改代码,不要无脑搬砖。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/901821.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号