首页 > 其他分享 >Playable API - 多个Animation Clip间切换播放

Playable API - 多个Animation Clip间切换播放

时间:2022-12-18 01:33:05浏览次数:58  
标签:Clip graph animClips API animMixerPlayable var using Playable playIndex

#

用到的脚本

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;

public class PlayAnimClipOneByOne : MonoBehaviour
{
    public AnimationClip[] animClips;

    private PlayableGraph _graph;
    private AnimationMixerPlayable _animMixerPlayable;

    private List<AnimationClipPlayable> _animClipPlayableList = new List<AnimationClipPlayable>();
    private int _playIndex = -1;

    void Start()
    {
        _graph = PlayableGraph.Create("ChanPlayableGraph");
        var animationOutputPlayable = AnimationPlayableOutput.Create(_graph, "AnimationOutput", GetComponent<Animator>()); //往graph添加output

        _animMixerPlayable = AnimationMixerPlayable.Create(_graph, animClips.Length); //往graph添加mixer
        animationOutputPlayable.SetSourcePlayable(_animMixerPlayable);

        for (var i = 0; i < animClips.Length; ++i)
        {
            var animClipPlayable = AnimationClipPlayable.Create(_graph, animClips[i]); //往graph添加playable
            _graph.Connect(animClipPlayable, 0, _animMixerPlayable, i);
            _animClipPlayableList.Add(animClipPlayable);
        }

        _playIndex = 0;
        _animMixerPlayable.SetInputWeight(_playIndex, 1);
        _graph.Play();
    }


    void Update()
    {
        if (Input.GetKeyDown(KeyCode.RightArrow)) //按右箭头播放下一个
        {
            var oldPlayIndex = _playIndex;
            _playIndex++;
            if (_playIndex >= animClips.Length)
                _playIndex = 0;

            if (oldPlayIndex >= 0)
                _animMixerPlayable.SetInputWeight(oldPlayIndex, 0); //停掉上一个

            //下一个从头开始播放
            _animMixerPlayable.SetInputWeight(_playIndex, 1);
            var curAnimClipPlayable = _animClipPlayableList[_playIndex];
            curAnimClipPlayable.SetTime(0);
            //curAnimClipPlayable.Play();

            if (!_graph.IsPlaying())
            {
                _graph.Play();
                Debug.Log($"graph play");
            }
        }
    }

}

运行效果:按->切换下一个动画

PlayableGraph的可视化图形:

参考

unity之 PlayableGraph 动画应用(二) - 赵不灰 - 博客园 (cnblogs.com)

【Unity】简单使用Playable API控制动画 - 知乎 (zhihu.com)

标签:Clip,graph,animClips,API,animMixerPlayable,var,using,Playable,playIndex
From: https://www.cnblogs.com/sailJs/p/16987666.html

相关文章