Documentation

Unity Engine

Download Unity

Unity Engine

BindTransforms

Matches each bone of a rig to a transform in a hierarchy, and outputs the transforms in a TransformAccessArray.
Read time 14 minutesLast updated 4 hours ago

Definition

BindTransforms(RigDefinition, Transform, TransformAccessArray)

Matches each bone of a rig to a transform in a hierarchy, and outputs the transforms in a TransformAccessArray.
public static void BindTransforms(ref RigDefinition rigDefinition, Transform rootTransform, out TransformAccessArray transformAccessArray)

Parameters

rigDefinition

The rig definition that contains the bones to bind.

rootTransform

The transform that the bone paths are relative to. The method searches the hierarchy under it, including itself.

transformAccessArray

The transform of each bone, indexed by bone index. You must dispose it.

Remarks

The method searches the hierarchy under
rootTransform
, including
rootTransform
itself. A transform matches a bone when the StringHash of its path relative to
rootTransform
equals the identifier of the bone.
rootTransform
has an empty path. If several transforms have the same path, the first one in depth-first order is used, and the method logs a warning and ignores the others and their child transforms. For a rig that you build from clips with RigBuilder, which follows the same rule, pass the same root transform. Transforms that aren't bones, such as the animated object above the skeleton root, aren't bound.
transformAccessArray
has one entry for each bone, indexed by bone index. The entry of a bone that has no matching transform is invalid. In an IJobParallelForTransform, the index that the job receives is the bone index, so use it to read the pose of the bone from an AnimationStream. Check TransformAccess.isValid before you write to the transform.
The method allocates memory, so call it once when you set up, not every frame. You must call TransformAccessArray.Dispose on
transformAccessArray
when you no longer need it.
Use this method when you write the pose in a job that runs while the main thread does other work. To write the pose on the main thread, use RigDefinitionUtility.BindTransforms instead, because scheduling a job and waiting for it at once costs more than it saves.
The following example animates a character in jobs each frame, and completes them before the frame renders. 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.
``<![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

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; } }}

BindTransforms(RigDefinition, Transform, Allocator, NativeArray<TransformHandle>)

Matches each bone of a rig to a transform in a hierarchy, and outputs the transform handle of each bone.
public static void BindTransforms(ref RigDefinition rigDefinition, Transform rootTransform, Allocator allocator, out NativeArray<TransformHandle> transformHandles)

Parameters

rigDefinition

The rig definition that contains the bones to bind.

rootTransform

The transform that the bone paths are relative to. The method searches the hierarchy under it, including itself.

allocator

The allocator for
transformHandles
. Use Allocator.Persistent or Allocator.TempJob if a job reads the array.

The transform handle of each bone, indexed by bone index. You must dispose it.

Remarks

The method searches the hierarchy under
rootTransform
, including
rootTransform
itself. A transform matches a bone when the StringHash of its path relative to
rootTransform
equals the identifier of the bone.
rootTransform
has an empty path. If several transforms have the same path, the first one in depth-first order is used, and the method logs a warning and ignores the others and their child transforms. For a rig that you build from clips with RigBuilder, which follows the same rule, pass the same root transform. Transforms that aren't bones, such as the animated object above the skeleton root, aren't bound.
transformHandles
has one entry for each bone, indexed by bone index. The entry of a bone that has no matching transform is TransformHandle.None.
Use this method when you need the TransformHandle of each bone, for example to add the transforms of several rigs to one TransformAccessArray. To get a TransformAccessArray for one rig, use RigDefinitionUtility.BindTransforms instead.
The method allocates memory, so call it once when you set up, not every frame. If a job reads
transformHandles
, don't use Allocator.Temp.
Each of the following examples is a
MonoBehaviour
that plays a clip on the hierarchy under its GameObject. It gets a rig definition and binds the transforms once. Each frame, it samples the clip into an animation stream and writes the pose to the transforms with a Burst-compiled function on the main thread. The first example builds the rig definition from the clip. The second example uses the rig definition that an Avatar stores. The last code block is the function that both examples use. The function isn't part of the API, so copy it into your project.
``<![CDATA[using Unity.Collections; using Unity.IntegerTime; using UnityEngine;
namespace Unity.Animations.DocumentationExamples { // This example plays a clip on the hierarchy under the GameObject of this component, with the rig definition that // an Avatar stores. Assign the Avatar of this hierarchy, and a clip that animates transforms under this GameObject. public class SampleClipWithAvatarExample : MonoBehaviour { public Avatar avatar; public AnimationClip animationClip;
BlobObjectReference<RigDefinition> m_RigReference; NativeArray<TransformHandle> m_BoneTransforms; ClipSampler m_Sampler; float m_Time;
void OnEnable() { if (avatar == null || animationClip == null) return;
// An Avatar stores a rig definition with a bone for each transform of the Avatar. The reference keeps the // rig definition alive until you dispose it, even if the Avatar is destroyed. m_RigReference = avatar.ToRigReference(); if (!m_RigReference.IsValid) { m_RigReference.Dispose(); m_RigReference = default; return; }
// Find the transform of each bone. The identifier of a bone of an Avatar is the StringHash of its path // relative to the root of the Avatar, so pass the transform that the Avatar was created from. RigDefinitionUtility.BindTransforms( ref m_RigReference.Value, transform, Allocator.Persistent, out m_BoneTransforms);
// Create the sampler once, and keep it between frames to sample faster. m_Sampler = animationClip.ToClipSampler(ref m_RigReference.Value, Allocator.Persistent); m_Time = 0f; }
void OnDisable() { // Dispose the sampler before the reference that keeps the rig definition alive. if (m_Sampler.IsCreated) m_Sampler.Dispose(); if (m_BoneTransforms.IsCreated) m_BoneTransforms.Dispose(); m_RigReference.Dispose(); }
void Update() { m_Time += Time.deltaTime; ApplyClipPose(m_Time); }
// Samples the clip at a time and writes the pose to the transforms. public void ApplyClipPose(float time) { // The sampler isn't created when the component has no Avatar or no clip. if (!m_Sampler.IsCreated) return;
// The stream starts with the default values of the rig, which are the local transforms of the hierarchy // when the Avatar was created. The sample overwrites only the channels that the clip animates. AnimationStream stream = AnimationStream.Create(ref m_RigReference.Value, Allocator.Temp);
// When the clip has Loop Time enabled, the time repeats. Otherwise, the pose stays at the end of the clip. m_Sampler.Sample(ref stream, new DiscreteTime(time));
// Write the pose to the transforms with a Burst-compiled function. The function isn't part of the API, // so copy it into your project. WriteTransformsUtility.WriteTransforms(stream, m_BoneTransforms);
// Dispose the stream explicitly, because a using declaration can't be passed by reference. stream.Dispose(); } } } ]]> ``<![CDATA[using Unity.Burst; using Unity.Collections; using Unity.Mathematics; using UnityEngine;
namespace Unity.Animations.DocumentationExamples { // Writes the pose in a stream to the transform handles that // RigDefinitionUtility.BindTransforms outputs. Entry index of the // handles is the transform of bone index. [BurstCompile] public static class WriteTransformsUtility { // A Burst-compiled static method runs on the main thread, so it // writes the transforms without the cost of scheduling a job. [BurstCompile] public static void WriteTransforms( in AnimationStream stream, in NativeArray<TransformHandle> transforms) { for (int i = 0; i < transforms.Length; ++i) { // The entry of a bone that has no transform is None, and a // destroyed transform is no longer valid. TransformHandle transform = transforms[i]; if (!transform.IsValid()) { continue; }
stream.GetLocalToParentTRS( i, out float3 translation, out quaternion rotation, out float3 scale); transform.SetLocalPositionAndRotation(translation, rotation); transform.localScale = scale; } } } } ]]>

Examples

using Unity.Collections;using Unity.IntegerTime;using UnityEngine;namespace Unity.Animations.DocumentationExamples{ // This example plays a clip on the hierarchy under the GameObject of this component. Assign a clip that animates // transforms under this GameObject, with paths relative to this GameObject. public class SampleClipToTransformsExample : MonoBehaviour { public AnimationClip animationClip; BlobObjectReference<RigDefinition> m_RigDefinition; NativeArray<TransformHandle> m_BoneTransforms; ClipSampler m_Sampler; float m_Time; void OnEnable() { if (animationClip == null) return; // Build a rig with a bone for each transform that the clip animates, and for each parent of those // transforms up to the transform of this component. using RigBuilder rigBuilder = RigBuilder.Create(transform, new[] { animationClip }, Allocator.Temp); m_RigDefinition = rigBuilder.ToRigDefinition(); // Find the transform of each bone. The array has one entry for each bone, indexed by bone index. The // entry of a bone that has no transform in the hierarchy is invalid. RigDefinitionUtility.BindTransforms( ref m_RigDefinition.Value, transform, Allocator.Persistent, out m_BoneTransforms); // Create the sampler once, and keep it between frames to sample faster. m_Sampler = animationClip.ToClipSampler(ref m_RigDefinition.Value, Allocator.Persistent); m_Time = 0f; } void OnDisable() { // Dispose the sampler before the rig definition that it uses. if (m_Sampler.IsCreated) m_Sampler.Dispose(); if (m_BoneTransforms.IsCreated) m_BoneTransforms.Dispose(); m_RigDefinition.Dispose(); } void Update() { m_Time += Time.deltaTime; ApplyClipPose(m_Time); } // Samples the clip at a time and writes the pose to the transforms. public void ApplyClipPose(float time) { // The sampler isn't created when the component has no clip. if (!m_Sampler.IsCreated) return; // The stream starts with the default values of the rig, which are the local transforms of the hierarchy // when the rig definition was created. The sample overwrites only the channels that the clip animates. AnimationStream stream = AnimationStream.Create(ref m_RigDefinition.Value, Allocator.Temp); // When the clip has Loop Time enabled, the time repeats. Otherwise, the pose stays at the end of the clip. m_Sampler.Sample(ref stream, new DiscreteTime(time)); // Write the pose to the transforms with a Burst-compiled function. The function isn't part of the API, // so copy it into your project. WriteTransformsUtility.WriteTransforms(stream, m_BoneTransforms); // Dispose the stream explicitly, because a using declaration can't be passed by reference. stream.Dispose(); } }}