Version: 6000.3
语言: 中文
播放动画剪辑
将动画剪辑与控制器混合

混合两个动画剪辑

此示例演示如何使用AnimationMixerPlayable以混合两个动画剪辑。

在此示例中,选择两个动画剪辑 (clip0clip1).在混合动画剪辑之前,必须将每个动画剪辑AnimationClipAnimationClipPlayable (clipPlayable0clipPlayable1).使用SetInputWeight()方法来动态调整每个可玩对象的混合权重。

您还可以使用AnimationMixerPlayable可播放剪辑与动画控制器混合

先决条件

在使用BlendAnimationClips脚本,则项目必须具有以下内容:

  • 一个游戏对象Unity 场景中的基本对象,可以表示角色、道具、风景、相机、航路点等。游戏对象的功能由附加到它的组件定义。更多信息
    请参阅术语表
    例如立方体或胶囊。您无需手动添加Animator 组件模型上的一个组件,使用动画系统为该模型设置动画。该组件具有对控制动画的 Animator 控制器资源的引用。更多信息
    请参阅术语表
    到这个游戏对象。这RequireComponent属性 添加此组件(如果不存在)。
  • 两个动画剪辑,用于对游戏对象的属性进行动画处理。为了使动画剪辑之间的混合明显,请使用两个彼此不同的剪辑。例如,一个剪辑对游戏对象的位置进行动画处理,而另一个剪辑对旋转进行动画处理。

添加并运行脚本

要使用BlendAnimationClipsscript,请按照以下步骤作:

  1. 将脚本组件添加到游戏对象。为脚本文件命名BlendAnimationClips.cs并使用以下代码:

    using UnityEngine;
    using UnityEngine.Playables;
    using UnityEngine.Animations;
    
    [RequireComponent(typeof(Animator))]
    public class BlendAnimationClips : MonoBehaviour
    {
    
        public AnimationClip clip0;
        public AnimationClip clip1;
        public float weight;
        PlayableGraph graph;
        AnimationMixerPlayable mixer;
    
        void Start()
        {
            // Create the graph and the mixer, then bind them to the Animator.
            graph = PlayableGraph.Create("BlendAnimationClips");
            mixer = AnimationMixerPlayable.Create(graph, 2);
    
            var output = AnimationPlayableOutput.Create(graph, "Animation", GetComponent<Animator>());
            output.SetSourcePlayable(mixer);
    
            // Create two AnimationClipPlayable playables, then connect them to the mixer.
            var clipPlayable0 = AnimationClipPlayable.Create(graph, clip0);
            var clipPlayable1 = AnimationClipPlayable.Create(graph, clip1);
    
            graph.Connect(clipPlayable0, 0, mixer, 0);
            graph.Connect(clipPlayable1, 0, mixer, 1);
    
            // Play the Graph.
            graph.Play();
        }
    
        void Update()
        {
            weight = Mathf.Clamp01(weight);
            mixer.SetInputWeight(0, 1.0f-weight);
            mixer.SetInputWeight(1, weight);
        }
    
        void OnDisable()
        {
            // Destroy all Playables and outputs created by the graph.
            graph.Destroy();
        }
    }
    
  2. 在 Script 组件中,选择动画剪辑 (clip0,clip1) 进行混合。

  3. 指定权重 (weight) 为两个剪辑。 该脚本会调整第一个剪辑相对于第二个剪辑的权重,以确保两个剪辑的权重等于 1.0。例如,权重为 0.2 时,第二个剪辑设置为 20% 的权重,将第一个剪辑设置为 80% 的权重。

  4. 选择 运行(Play) 将编辑器切换到播放模式。

  5. 在 脚本 组件中,尝试不同的权重。

  6. 如果您已安装 PlayableGraph Visualizer 包,请选择BlendAnimationClips以显示 PlayableGraph。

由 BlendAnimationClips 脚本生成的 PlayableGraph
BlendAnimationClips脚本

其他资源

播放动画剪辑
将动画剪辑与控制器混合