unity使用脚本动态替换动画 并添加帧事件

unity使用脚本动态替换动画 并添加帧事件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(SpriteRenderer))]
public class ReplaceAnimation : MonoBehaviour
{
    private RuntimeAnimatorController run;

    public Animator anima;
    void Start()
    {
        //获取自身的Animator组件
        anima = GetComponent<Animator>();
    }

    public void Replace(AnimationClip clip) {
        //重要!!预先保存
        run = anima.runtimeAnimatorController;

        var ride = new AnimatorOverrideController();

        ride.runtimeAnimatorController = anima.runtimeAnimatorController;
        //这里是需要替换的动画的名字,并非状态的名字
        ride["play"] = clip;

        //新建帧事件
        var _event = new AnimationEvent();
        //要添加的方法名,暂时只用无参方法
        _event.functionName = "PlayEvent";
        //帧时间触发的事件,相当于百分比 1代表结尾时
        _event.time = 1f;
        //添加帧时间到动画中
        ride["play"].AddEvent(_event);
        //重新绑定一下动画 从其他文章中学来 原理未知
        anima.Rebind();
        //先置空,再赋值,不然会产生错乱
        anima.runtimeAnimatorController = null;
        anima.runtimeAnimatorController = ride;

        anima.Play("play", 0, 0);
        
        
    }

    public void PlayEvent() {
        //这里是帧事件触发的方法,也可以在这里运行事件
        Destroy(gameObject);
        //如果不是销毁,需要重复使用游戏物体的话,需要把之前保存的runtimeAnimatorController重新赋回
        anima.runtimeAnimatorController = run;
    }
}

这个方法解决了特效池替换序列帧特效的需求 尚有优化空间

你可能感兴趣的:(unity使用脚本动态替换动画 并添加帧事件)