Playable API - 多个Animation Clip间切换播放
思路:AnimationMixerPlayable可以关联多个AnimationClip,通过SetInputWeight(index, 1)来让某个AnimationClip播放,SetInputWeight(index, 0)停止播放;
然后AnimationPlayableOutput从AnimationMixerPlayable接收输入,最后输出到PlayableGraph。
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.Connect函数
上面用到的Connect(AnimationClipPlayable src, int srcOutputPort, AnimationMixerPlayable dst, int dstInputPort)
a) 可以把src看做是电脑显卡的hdmi输出口,集成显卡一般只有1个,所以默认一般都用0;高端的显卡有2个甚至更多
b) 把dst看做是显示器的hdmi输入口,电脑A接了输入口0,那电脑B就没法接了;如果也想接,那必定电脑A会被替换掉(拔掉电脑A的);但电脑B接输入口1,就能让电脑A和电脑B都接在显示器上。
所以常见的用法都是:
Connect(pcA, 0, displayA, 0)
Connect(pcB, 0, displayA, 1)
运行效果:按->切换下一个动画
PlayableGraph的可视化图形: