unity之 PlayableGraph 动画应用(二)
续上篇 unity之性能优化 PlayableGraph 动画应用(一)继续:
多个动画如何播放,动画融合、权重等
上代码:
1 using System.Collections.Generic;
2 using UnityEngine;
3 using UnityEngine.Animations;
4 using UnityEngine.Playables;
5
6 public class TestPlayable : MonoBehaviour
7 {
8 private Animator m_Animator;
9
10 [SerializeField]
11 private AnimationClip m_AnimationClip;
12 private PlayableGraph m_PlayableGraph;
13 private AnimationPlayableOutput m_AnimationPlayableOutput;
14
15 void Awake()
16 {
17 m_Animator = GetComponent<Animator>();
18 //创建画布
19 m_PlayableGraph = PlayableGraph.Create("testGraph");
20 //为画布创建一个输出节点
21 m_AnimationPlayableOutput = AnimationPlayableOutput.Create(m_PlayableGraph, "OutPut", m_Animator);
22 Test2();
23 }
24
25 [SerializeField]
26 private AnimationClip[] m_Clips;
27 //动画剪辑Playable列表
28 private List<AnimationClipPlayable> m_AnimationClipPlayable = new List<AnimationClipPlayable>(100);
29 //动画混合
30 private AnimationMixerPlayable m_AnimationMixerPlayable;
31
32 /// <summary>
33 /// 目的是为了 画出图形
34 /// </summary>
35 private void Test2()
36 {
37 int clipCount = m_Clips.Length;
38 //创建动画混合
39 m_AnimationMixerPlayable = AnimationMixerPlayable.Create(m_PlayableGraph, clipCount);
40 //设置output的源头 动画混合
41 m_AnimationPlayableOutput.SetSourcePlayable(m_AnimationMixerPlayable, 0);
42
43 for (int i = 0; i < clipCount; i++)
44 {
45 //创建动画剪辑
46 AnimationClipPlayable animationClipPlayable = AnimationClipPlayable.Create(m_PlayableGraph, m_Clips[i]);
47 //画布连接动画混合、动画剪辑从index = 0到index = count-1 全部跟动画融合相连
48 m_PlayableGraph.Connect(animationClipPlayable, 0, m_AnimationMixerPlayable, i);
49 m_AnimationClipPlayable.Add(animationClipPlayable);
50 }
51 }
52 }
以上代码 运行起来:绘制的画布如下:
好 播放的代码:
1 private int index = 0;
2 private void Play()
3 {
4 m_PlayableGraph.Play();
5 //通过索引获取playable
6 Playable playable = m_AnimationMixerPlayable.GetInput(index);
7 playable.SetTime(0);
8 playable.Play();
9 int count = m_AnimationClipPlayable.Count;
10 for (int i = 0; i < count; i++)
11 {
12 if (i == index)
13 {
14 //需要播放的权重设置为1
15 m_AnimationMixerPlayable.SetInputWeight(i, 1);
16 }
17 else
18 {
19 //不播放的权重设置为0
20 m_AnimationMixerPlayable.SetInputWeight(i, 0);
21 }
22 }
23 index++;
24 if (index == count)
25 {
26 index = 0;
27 }
28 }
29
30 void Update()
31 {
32 if (Input.GetKeyUp(KeyCode.P))
33 {
34 Play();
35 }
36 }
好了,以上就是 PlayableGraph 动画应用(二)混合动画的播放。