This example demonstrates how to use a AnimationMixerPlayable to blend two animation clips.
In this example, you select two animation clips (clip0 and clip1). Before you blend the animation clips, you must wrap each AnimationClip in an AnimationClipPlayable (clipPlayable0 and clipPlayable1). Use the SetInputWeight() method to dynamically adjust the blend weight of each playable.
You can also use a AnimationMixerPlayable to blend a playable clip with an animation controller.
Before you use the BlendAnimationClips script in your project, your project must have the following:
RequireComponent attribute adds this component if it’s not present.To use the BlendAnimationClips script in your project, follow these steps:
Add a script component to your GameObject. Name the script file BlendAnimationClips.cs and use the following code:
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();
}
}
In the Script component, select the animation clips (clip0, clip1) for the blend.
Specify a weight (weight) for both clips.
The script adjusts the weight of the first clip in relation to the second clip to ensure that the weight of both clips equals 1.0. For example, a weight of 0.2 sets the second clip to 20% weight and the first clip to 80% weight.
Select Play to switch the Editor to Play mode.
In the Script component, experiment with different weights.
If you have installed the PlayableGraph Visualizer package, select BlendAnimationClips to display the PlayableGraph.
BlendAnimationClips script