Documentation

Unity Engine

Download Unity

Unity Engine

ClipSampler

Samples an animation clip into an AnimationStream, and returns the root motion of the clip.
Read time 13 minutesLast updated 3 hours ago

Definition

public struct ClipSampler : IDisposable

Remarks

A clip sampler needs no Animator or PlayableGraph, and writes to an AnimationStream, not to GameObjects. Don't confuse it with AnimationClipPlayable or
AnimationClip.SampleAnimation
, which animate GameObjects.
A clip sampler reads an animation clip at a given time. It computes the value of each curve of the clip at that time, and writes that value to the matching channel of an animation stream. It also reports how far the root of the clip moved.
Call AnimationClipExtensions.ToClipSampler from the main thread to create a sampler for a clip and a rig. Call ClipSampler.Dispose when you finish with it. Then use the sampler as follows:
  • ClipSampler.Sample overwrites the channels that the clip animates and leaves the others unchanged.
  • ClipSampler.SampleAdditive resets the whole stream to zero, samples the clip, and subtracts the additive reference pose of the clip, or its start pose, like an additive layer of an Animator. The stream then holds an additive pose.
  • ClipSampler.SampleRootMotion returns how much the root of the clip moved from the previous time of a timer to its current time, and the root transform at the current time.
  • ClipSampler.SampleExtractingRootMotion samples as
    Sample
    does and keeps the root motion out of the pose, so that the character moves only with the root motion that you apply.
Sample
and
SampleAdditive
each have a TimerState overload and a DiscreteTime overload. The remarks of each method explain which one to use. The sampler is faster when the time moves forward. When the time on the clip curves goes backward, for example when a looping clip wraps around, the sampler restarts from the beginning of the clip data.
Keep these rules in mind:
  • Creating a sampler is expensive. Create one sampler for each pair of clip and rig, keep it, and call ClipSampler.Clone to get more samplers for the same clip and rig. Create the sampler again to sample an edited clip.
  • Copies of the struct share the same memory. Dispose only one copy. A clone has its own memory, so dispose each clone too.
  • Use a sampler from one job at a time, and from one thread at a time. If safety checks are enabled, the job system throws an
    InvalidOperationException
    when two scheduled jobs write the same sampler.
  • Don't store a sampler in a component or a buffer element. If safety checks are enabled, the job system refuses to schedule a job that accesses a component that holds a native container. To animate many characters, create one sampler for each character, keep the samplers of a group of characters in an UnsafeList<T>, and sample them in one job. The job scheduler can't see the samplers behind the list, so it doesn't detect jobs that use the same sampler. Safety checks still detect the use of a disposed sampler.
Safety checks are always enabled in the Editor and never in a built Player.
The following examples use the
Unity.Animations
,
Unity.Burst
,
Unity.Collections
,
Unity.Collections.LowLevel.Unsafe
,
Unity.Entities
,
Unity.IntegerTime
,
Unity.Jobs
, and
UnityEngine
namespaces. The first example samples the
intensity
field of the
SampleClipExampleTarget
component at a given time into an animation stream. To run it, add a
MonoBehaviour
named
SampleClipExampleTarget
that has a
float
field named
intensity
, or replace the component and the field with the ones that your animation clip animates. The second example samples one clip for several characters in a Burst-compiled job. The third example animates a character in Burst-compiled jobs each frame: it samples and blends two clips, solves foot IK, and writes the pose to the transforms.
The last code block is the job that writes the pose to the transforms. The job isn't part of the API, so copy it into your project.
Additional Resources: AnimationClipExtensions
``<![CDATA[ // This job samples the intensity field of several characters. Each character has its own sampler, in a list // that is not seen by the job system. Do not schedule two jobs that use the same sampler at the same time. // The job holds a BlobObjectReference to the rig, which keeps the rig alive while the job runs. [BurstCompile] struct SampleCharactersJob : IJob { public UnsafeList<ClipSampler> Samplers; public BlobObjectReference<RigDefinition> Rig; public DiscreteTime Time; public NativeArray<float> Intensities;
public void Execute() { // The job creates one stream for all characters, because it samples them one after the other. AnimationStream stream = AnimationStream.Create(ref Rig.Value, Allocator.Temp);
for (int i = 0; i < Samplers.Length; ++i) { // Use ElementAt to sample the sampler in the list, not a copy of it. Samplers.ElementAt(i).Sample(ref stream, Time); Intensities[i] = stream.GetFloat(0); }
stream.Dispose(); } }
// This example samples the intensity field of the same clip for several characters at a given time. The // rig has one float channel, as in SampleClipExample. The caller disposes the returned array. public static NativeArray<float> SampleIntensities( AnimationClip animationClip, int characterCount, float time) { using RigBuilder rigBuilder = new RigBuilder(Allocator.Temp); rigBuilder.Add(FloatChannel.Create( "", typeof(SampleClipExampleTarget), nameof(SampleClipExampleTarget.intensity), 0f)); using BlobObjectReference<RigDefinition> rigDefinition = rigBuilder.ToRigDefinition();
// Create one sampler from the main thread, then clone it for the other characters. Creating a sampler // matches the curves of the clip with the rig, which is expensive. A clone only copies memory. The // samplers share the clip data. UnsafeList<ClipSampler> samplers = new UnsafeList<ClipSampler>(characterCount, Allocator.Persistent); if (characterCount > 0) samplers.Add(animationClip.ToClipSampler(ref rigDefinition.Value, Allocator.Persistent)); for (int i = 1; i < characterCount; ++i) samplers.Add(samplers[0].Clone());
NativeArray<float> intensities = new NativeArray<float>(characterCount, Allocator.TempJob); new SampleCharactersJob { Samplers = samplers, Rig = rigDefinition, Time = new DiscreteTime(time), Intensities = intensities, }.Run();
// Dispose each sampler, then the list. for (int i = 0; i < samplers.Length; ++i) samplers[i].Dispose(); samplers.Dispose();
return intensities; } ]]> ``<![CDATA[using Unity.Burst; using Unity.Collections; using Unity.IntegerTime; using Unity.Jobs; using Unity.Mathematics; using UnityEngine; using UnityEngine.Jobs;
namespace Unity.Animations.DocumentationExamples { // This example animates a character in Burst-compiled jobs each frame. The first job advances the time, samples // a walk clip and a run clip, blends them, and places the left foot on a target with two-bone IK. The second job // writes the pose to the transforms. Assign the clips, the skeleton root, the bones of the left leg, and the foot // target, and set the run weight from the speed of the character. The skeleton root is the top bone of the // skeleton, a direct child of this GameObject. public class CharacterAnimationExample : MonoBehaviour { public AnimationClip walkClip; public AnimationClip runClip; public Transform skeletonRootTransform; public Transform leftUpperLeg; public Transform leftLowerLeg; public Transform leftFoot; public Transform leftFootTarget; [Range(0f, 1f)] public float runWeight;
BlobObjectReference<RigDefinition> m_Rig; ClipSampler m_WalkSampler; ClipSampler m_RunSampler; NativeArray<TimerState> m_Timers; NativeArray<AnimatedData> m_WalkPose; NativeArray<AnimatedData> m_RunPose; NativeArray<AnimatedData> m_Output; TransformAccessArray m_Transforms; int m_UpperLegIndex; int m_LowerLegIndex; int m_FootIndex; JobHandle m_Frame;
[BurstCompile] struct AnimateCharacterJob : IJob { public ClipSampler WalkSampler; public ClipSampler RunSampler; // The timers live in a native array, because the job system copies the job struct. public NativeArray<TimerState> Timers; // A stream can't be a job field. The job stores the rig and the pose buffers, and creates the streams in // Execute. public BlobObjectReference<RigDefinition> Rig; public NativeArray<AnimatedData> WalkPose; public NativeArray<AnimatedData> RunPose; public NativeArray<AnimatedData> Output; public float RunWeight; public float DeltaTime; public float WalkLength; public float RunLength; public Core.TwoBoneIKData FootIK;
public void Execute() { AnimationStream walkStream = AnimationStream.Create(ref Rig.Value, WalkPose); AnimationStream runStream = AnimationStream.Create(ref Rig.Value, RunPose); AnimationStream output = AnimationStream.Create(ref Rig.Value, Output);
// Keep the clips in step: both take the same time to play a cycle, which is a blend of their lengths. // A walk and a run that start with the same foot then keep their feet in phase. float cycleLength = math.lerp(WalkLength, RunLength, RunWeight); TimerState walkTimer = Timers[0]; TimerState runTimer = Timers[1]; walkTimer.Update(new DiscreteTime(DeltaTime * WalkLength / cycleLength)); runTimer.Update(new DiscreteTime(DeltaTime * RunLength / cycleLength)); Timers[0] = walkTimer; Timers[1] = runTimer;
WalkSampler.Sample(ref walkStream, walkTimer); RunSampler.Sample(ref runStream, runTimer); output.Blend(walkStream, runStream, RunWeight);
// The rig has a bone for each transform that the clips animate and for their parents, so a leg that the // clips don't animate has no bones. if (FootIK.RootIndex >= 0 && FootIK.MidIndex >= 0 && FootIK.TipIndex >= 0) Core.SolveTwoBoneIK(ref output, FootIK, 1f); } }
void OnEnable() { if (walkClip == null || runClip == null || skeletonRootTransform == null) return;
// Create everything that the jobs use once, and keep it between frames. The reference keeps the rig // definition alive until you dispose it. using RigBuilder rigBuilder = RigBuilder.Create( transform, skeletonRootTransform, new[] { walkClip, runClip }, Allocator.Temp); m_Rig = rigBuilder.ToRigDefinition(); m_WalkSampler = walkClip.ToClipSampler(ref m_Rig.Value, Allocator.Persistent); m_RunSampler = runClip.ToClipSampler(ref m_Rig.Value, Allocator.Persistent); m_Timers = new NativeArray<TimerState>(2, Allocator.Persistent); m_Timers[0] = TimerState.Create(new DiscreteTimeInterval(DiscreteTime.Zero, new DiscreteTime(walkClip.length)), WrapMode.Loop); m_Timers[1] = TimerState.Create(new DiscreteTimeInterval(DiscreteTime.Zero, new DiscreteTime(runClip.length)), WrapMode.Loop);
// Keep a buffer for each pose, and start from the default values of the rig. int streamSize = m_Rig.Value.Bindings.StreamSize; m_WalkPose = new NativeArray<AnimatedData>(streamSize, Allocator.Persistent); m_RunPose = new NativeArray<AnimatedData>(streamSize, Allocator.Persistent); m_Output = new NativeArray<AnimatedData>(streamSize, Allocator.Persistent); AnimationStream walkPose = AnimationStream.Create(ref m_Rig.Value, m_WalkPose); walkPose.ResetToDefaultValues(); AnimationStream runPose = AnimationStream.Create(ref m_Rig.Value, m_RunPose); runPose.ResetToDefaultValues(); AnimationStream output = AnimationStream.Create(ref m_Rig.Value, m_Output); output.ResetToDefaultValues();
// A transform access array holds the transforms that the write job can change, indexed by bone index. RigDefinitionUtility.BindTransforms(ref m_Rig.Value, transform, out m_Transforms);
// Find the bones of the leg once. m_UpperLegIndex = FindBoneIndex(leftUpperLeg); m_LowerLegIndex = FindBoneIndex(leftLowerLeg); m_FootIndex = FindBoneIndex(leftFoot); }
void OnDisable() { if (!m_Rig.IsValid) return;
// Wait for the jobs before disposing what they use, and dispose the samplers and pose buffers before the rig. m_Frame.Complete(); m_Transforms.Dispose(); m_Output.Dispose(); m_RunPose.Dispose(); m_WalkPose.Dispose(); m_Timers.Dispose(); m_RunSampler.Dispose(); m_WalkSampler.Dispose(); m_Rig.Dispose(); }
void Update() { m_Frame = ScheduleFrame(Time.deltaTime); }
void LateUpdate() { // Other scripts run while the jobs work. Complete them before the frame renders. m_Frame.Complete(); }
// Schedules the jobs for one frame and returns the handle of the last job. public JobHandle ScheduleFrame(float deltaTime) { if (!m_Rig.IsValid) return default;
// The IK target is in character space, which is the space of this GameObject. Core.TwoBoneIKData footIK = Core.TwoBoneIKData.Default(); footIK.RootIndex = m_UpperLegIndex; footIK.MidIndex = m_LowerLegIndex; footIK.TipIndex = m_FootIndex; footIK.Target = new RigidTransform( Quaternion.Inverse(transform.rotation) * leftFootTarget.rotation, transform.InverseTransformPoint(leftFootTarget.position));
var animate = new AnimateCharacterJob { WalkSampler = m_WalkSampler, RunSampler = m_RunSampler, Timers = m_Timers, Rig = m_Rig, WalkPose = m_WalkPose, RunPose = m_RunPose, Output = m_Output, RunWeight = runWeight, DeltaTime = deltaTime, WalkLength = walkClip.length, RunLength = runClip.length, FootIK = footIK }; // The write job isn't part of the API, so copy it into your project. var write = new WriteTransformsJob { Rig = m_Rig, Pose = m_Output };
// The write job reads the pose that the animate job writes, so it depends on it. JobHandle animated = animate.Schedule(); return write.Schedule(m_Transforms, animated); }
// Returns the bone index of a transform, or -1 if no bone has the transform. int FindBoneIndex(Transform bone) { if (bone == null) return -1; for (int i = 0; i < m_Transforms.length; ++i) { if (m_Transforms[i] == bone) return i; } return -1; } } } ]]> ``<![CDATA[using Unity.Burst; using Unity.Collections; using Unity.Mathematics; using UnityEngine; using UnityEngine.Jobs;
namespace Unity.Animations.DocumentationExamples { // Writes a pose to the transforms that // RigDefinitionUtility.BindTransforms outputs. Entry index of the // TransformAccessArray is the transform of bone index. [BurstCompile] public struct WriteTransformsJob : IJobParallelForTransform { // A stream can't be a job field, so the job stores the rig and // the pose buffer, and creates the stream in Execute. public BlobObjectReference<RigDefinition> Rig; [ReadOnly] public NativeArray<AnimatedData> Pose;
public void Execute(int index, TransformAccess transform) { // The entry of a bone that has no transform is invalid. if (!transform.isValid) { return; }
AnimationStream stream = AnimationStream.CreateReadOnly(ref Rig.Value, Pose); stream.GetLocalToParentTRS( index, out float3 translation, out quaternion rotation, out float3 scale); transform.SetLocalPositionAndRotation(translation, rotation); transform.localScale = scale; } } } ]]>

Examples

// This example samples the intensity field that a clip animates at a given time and returns the sampled value.public static float SampleIntensity(AnimationClip animationClip, float time){ // Describe the animated field in a rig, so that the animation stream has a slot for it. using RigBuilder rigBuilder = new RigBuilder(Allocator.Temp); // The empty path means that the animated component is on the root object. The last argument is the // default value. rigBuilder.Add(FloatChannel.Create( "", typeof(SampleClipExampleTarget), nameof(SampleClipExampleTarget.intensity), 0f)); using BlobObjectReference<RigDefinition> rigDefinition = rigBuilder.ToRigDefinition(); // Create a sampler for the clip and the rig, from the main thread. // Keep the sampler between samples of the same clip to sample faster. using ClipSampler sampler = animationClip.ToClipSampler(ref rigDefinition.Value, Allocator.Persistent); // Stop if the sampler isn't created, for example when the animation clip is null. if (!sampler.IsCreated) { return 0f; } // Create the animation stream that receives the sampled values. The stream owns its buffer. AnimationStream stream = AnimationStream.Create(ref rigDefinition.Value, Allocator.Temp); // Sample the clip at the given time. The sample overwrites the content of the stream. sampler.Sample(ref stream, new DiscreteTime(time)); float intensity = stream.GetFloat(0); // Dispose the stream explicitly, because a using declaration can't be passed by reference. stream.Dispose(); // For a clip that goes from 0 to 10 over one second, the sample at 0.5 seconds is 5. return intensity;}

Properties

Property

Description

ClipThe reference to the clip data that the sampler samples.
HasRootMotionWhether the clip has root motion curves for the rig of the sampler.
IsCreatedWhether the sampler has allocated memory.

Methods

Method

Description

CloneCreates a sampler that samples the same clip for the same rig, with its own memory.
DisposeReleases the clip reference and the memory of the sampler.
SampleSamples the clip at the time of a clip timer. The method computes the value of each curve of the clip at that time, and overwrites the matching channels of the animation stream.
SampleAdditiveSamples the clip at the time of a clip timer, relative to its reference pose, into a stream that you can apply as an additive pose.
SampleExtractingRootMotionSamples the clip with a clip timer, and removes the root motion from the pose, as an Animator does when it applies root motion.
SampleRootMotionSamples how much the root of the clip moved from the previous time to the time of a clip timer, and the root transform at that time.