Code-driven 2D and 3D animation controller for Unity 6 built directly on the Playables API. It plays 2D Sprite AnimationClip assets and 3D skeletal rigs on a standard Animator component without requiring an AnimatorController state graph.
- Direct Playables pipeline (
PlayableAnimGraph): DrivesPlayableGraph,AnimationLayerMixerPlayable, and per-layer 2-inputAnimationMixerPlayableslots from pure C#, with optionalmanualUpdateModefor deterministic stepping or EditMode tests. - 2D and 3D playback support: Pass
fadeDuration: 0ffor instant 2D frame-by-frame clip switching, or positive durations for linear 3D skeletal cross-fades. - Masked and additive layers (
AnimLayerConfig): Configure per-layerdefaultWeight,AvatarMask, andisAdditiveflags onCustomAnimController, or fade overlay layers back out viaStopLayer(layer, fadeOutDuration). - Priority locks and normalized-time events (
AnimPlayRequest,AnimClipEvent): Keep lower-priority clips from interrupting higher-priority actions until a non-looping clip finishes, and invoke C# callbacks when playback crosses[0, 1]clip markers (including across loop wrap-arounds). - Keyed clip sets (
AnimSetAsset): OptionalScriptableObjectmapping case-sensitive string keys to clips, default fade times, speeds, layers, priorities, and optionalnextKeyOnCompletechaining viaPlayByKey. - Optional code state machine (
AnimStateMachine): Register namedAnimStateDefinitionentries, prioritizedIAnimTransitionRulepredicates,"*"any-state rules, enter/exit hooks, and automatic return states on clip completion. - UI Toolkit inspection and debugging: Ships with
CustomAnimInspectorandAnimDebuggerWindow(Tools > HaruChanZ64 > Animation > PlayablesAnimatorController > Animation Debugger) showing live layer progress bars, cross-fade weights, recent clip history, and manual test playback controls.
- Unity
6000.0or newer - Zero required external dependencies
- Open Window > Package Manager in Unity 6 (
6000.0+). - Click + (top-left) and choose Install package from git URL....
- Enter:
https://github.com/haruchanz64/PlayablesAnimatorController.git
Add the package path to Packages/manifest.json:
{
"dependencies": {
"com.haruchanz64.playables-animator-controller": "file:../Plugins/PlayablesAnimatorController"
}
}- Add
CustomAnimControllerto any GameObject with anAnimatorcomponent (it enforces[RequireComponent(typeof(Animator))]). Leave theAnimatorcomponent's Controller field empty. - (Optional) Configure additional entries in the Layers list on
CustomAnimController(for example, layer1with an upper-bodyAvatarMaskanddefaultWeight = 0). - (Optional) Create a keyed clip library via Assets > Create > PlayablesAnimatorController > Animation Set, populate its
entrieslist, assign it toAnimation SetonCustomAnimController, and setInitial Keyto play a starting clip automatically onOnEnable. - Drive clips from your gameplay scripts using
CustomAnimController.Play(...),CustomAnimController.PlayByKey(...), or anAnimStateMachine. - Enter Play Mode and open Tools > HaruChanZ64 > Animation > PlayablesAnimatorController > Animation Debugger (or click Open Animation Debugger in the
CustomAnimControllerInspector) to monitor layer progress, cross-fade weights, and clip history, or trigger manual test clips.
PlayableAnimGraph connects a single AnimationLayerMixerPlayable to an AnimationPlayableOutput bound to the target Animator. Each layer owns a 2-input AnimationMixerPlayable:
- Port 0 (active clip): Receives the newly created
AnimationClipPlayable. - Port 1 (outgoing clip): Holds the previous clip when
FadeDuration > 0.0001fand a valid active playable already exists. DuringTick(deltaTime), port 0 ramps linearly from0to1while port 1 ramps from1to0, and port 1 is disconnected and destroyed once blending finishes. - Instant switches: When
FadeDuration <= 0.0001f(typical for 2D sprites), the previous active playable is destroyed immediately and port 0 starts at weight1. - On-demand layer expansion: Playing on a layer index greater than or equal to
LayerCountexpands_layerMixerautomatically so code can target higher layers without throwing out-of-range errors.
- Priority gating: While a layer has an active, incomplete clip (
IsPlaying && !HasCompleted), requests withrequest.Priority < activePriorityreturnfalseunlessrequest.ForceOverridePriorityistrue. Once a non-looping clip reachestime >= clip.length,HasCompletedbecomestrue,Priorityresets to0,request.OnCompletefires, andOnClipCompletedis raised. - Same-clip guard: Re-requesting the currently active, incomplete clip with
RestartIfSame == falsekeeps playback running without restarting and updates the playable's speed torequest.Speed. - Normalized-time events (
AnimClipEvent): EachTickchecks markers in[prevNorm, currNorm]so events fire once per pass without frame-rate dependence. On looping clips, crossing a loop boundary fires remaining tail markers up to1.0, resets fired flags, incrementsLoopCount, and fires early markers in[0.0, currNorm].
AnimStateMachine operates on any IAnimationDriver and a single target layer (layer = 0 by default). On each Tick():
- Registered
IAnimTransitionRuleinstances are sorted lazily in descendingPriorityorder. - The first matching rule (
FromStateId == "*"or ordinal match withCurrentStateId, excluding self-transitions) whoseEvaluate(in AnimPlaybackState)returnstruecallsTrySetState(rule.ToStateId). - If no transition triggers and the active state's clip has
HasCompleted == truewith a non-emptyAutoReturnStateId, the machine transitions toAutoReturnStateIdwithforceOverridePriority: true.
using PlayablesAnimatorController.Components;
using PlayablesAnimatorController.Core;
using UnityEngine;
public sealed class PlayerAnimator : MonoBehaviour
{
[SerializeField] private CustomAnimController anim;
[SerializeField] private AnimationClip idleClip;
[SerializeField] private AnimationClip runClip;
[SerializeField] private AnimationClip upperBodySlashClip;
public void UpdateLocomotion(bool isMoving)
{
anim.Play(isMoving ? runClip : idleClip, fadeDuration: 0.15f, layer: 0);
}
public void PlayUpperBodySlash()
{
var req = AnimPlayRequest.Create(
upperBodySlashClip,
fadeDuration: 0.08f,
layer: 1,
priority: 10,
restartIfSame: true,
onComplete: () => anim.StopLayer(1, fadeOutDuration: 0.12f),
stateId: "UpperSlash");
req.Events = new[]
{
new AnimClipEvent(0.45f, () => Debug.Log("Hitbox active"))
};
anim.Play(in req);
}
}Assign an AnimSetAsset to CustomAnimController.AnimationSet in the Inspector (or via code) to play clips by string key and optionally override fade duration or target layer:
using PlayablesAnimatorController.Components;
using UnityEngine;
public sealed class KeyedCharacterAnimator : MonoBehaviour
{
[SerializeField] private CustomAnimController anim;
public void TriggerDodge()
{
// Uses entry defaults from AnimSetAsset and chains nextKeyOnComplete automatically.
anim.PlayByKey("Dodge", fadeOverride: 0.05f);
}
public void TriggerEmoteOnOverlay()
{
anim.PlayByKey("Wave", layerOverride: 1);
}
}Implement IAnimTransitionRule for reusable transition logic (such as exit-time gates or shared character checks) and register it alongside states on AnimStateMachine:
using System;
using PlayablesAnimatorController.Components;
using PlayablesAnimatorController.Core;
using PlayablesAnimatorController.States;
using UnityEngine;
public sealed class ExitTimeTransitionRule : IAnimTransitionRule
{
private readonly float _minNormalizedTime;
private readonly Func<bool> _condition;
public string FromStateId { get; }
public string ToStateId { get; }
public int Priority { get; }
public ExitTimeTransitionRule(
string fromStateId,
string toStateId,
float minNormalizedTime,
Func<bool> condition,
int priority = 0)
{
FromStateId = fromStateId;
ToStateId = toStateId;
_minNormalizedTime = Mathf.Clamp01(minNormalizedTime);
_condition = condition;
Priority = priority;
}
public bool Evaluate(in AnimPlaybackState currentState)
{
return currentState.NormalizedTime >= _minNormalizedTime && _condition();
}
}
[RequireComponent(typeof(CustomAnimController))]
public sealed class ComboStateDriver : MonoBehaviour
{
[SerializeField] private AnimationClip idleClip;
[SerializeField] private AnimationClip combo1Clip;
[SerializeField] private AnimationClip combo2Clip;
private AnimStateMachine _fsm;
private bool _comboQueued;
private void Awake()
{
var anim = GetComponent<CustomAnimController>();
_fsm = new AnimStateMachine(anim, layer: 0);
_fsm.RegisterState("Idle", idleClip, fadeDuration: 0.1f)
.RegisterState(new AnimStateDefinition
{
StateId = "Combo1",
Clip = combo1Clip,
FadeDuration = 0.05f,
Priority = 10,
AutoReturnStateId = "Idle",
OnEnter = () => _comboQueued = false
})
.RegisterState("Combo2", combo2Clip, fadeDuration: 0.05f, priority: 10, autoReturnStateId: "Idle");
_fsm.AddTransition(new ExitTimeTransitionRule(
fromStateId: "Combo1",
toStateId: "Combo2",
minNormalizedTime: 0.6f,
condition: () => _comboQueued,
priority: 20));
_fsm.TrySetState("Idle");
}
private void Update() => _fsm.Tick();
public void PressAttack()
{
if (_fsm.CurrentStateId == "Combo1")
{
_comboQueued = true;
return;
}
_fsm.TrySetState("Combo1");
}
}For custom update schedulers, timeline previews, or EditMode unit tests, construct PlayableAnimGraph directly with manualUpdateMode: true and dispose it when finished:
using PlayablesAnimatorController.Core;
using UnityEngine;
public sealed class ManualGraphStepper
{
public static void StepClip(Animator animator, AnimationClip clip, float dt)
{
using var graph = new PlayableAnimGraph(animator, "ManualPreview", manualUpdateMode: true);
graph.Play(AnimPlayRequest.Create(clip, fadeDuration: 0f));
graph.Tick(dt);
AnimPlaybackState state = graph.GetLayerState(0);
Debug.Log($"{state.StateId}: {state.NormalizedTime:P0}");
}
}| Type | Namespace | Purpose | Built-in implementation |
|---|---|---|---|
IAnimationDriver |
PlayablesAnimatorController.Core |
Unified playback contract for clip playback, keyed lookups, layer weights, speed, and state queries | CustomAnimController (plus mock drivers in tests) |
PlayableAnimGraph |
PlayablesAnimatorController.Core |
Pure C# IDisposable wrapper around PlayableGraph, AnimationLayerMixerPlayable, and per-layer cross-fade mixers |
PlayableAnimGraph |
CustomAnimController |
PlayablesAnimatorController.Components |
MonoBehaviour attaching a PlayableAnimGraph to an Animator with AnimSetAsset support and debugger history |
CustomAnimController |
AnimPlayRequest |
PlayablesAnimatorController.Core |
Value struct describing clip, layer, fade duration, speed, start time, priority, completion callback, and events | AnimPlayRequest.Create(...) |
AnimClipEvent |
PlayablesAnimatorController.Core |
Readonly struct pairing a [0, 1] normalized marker with a callback |
AnimClipEvent |
AnimPlaybackState |
PlayablesAnimatorController.Core |
Observable snapshot of a layer's active/previous clips, timing, weights, loop count, completion, and priority | Returned by GetLayerState |
AnimLayerConfig |
PlayablesAnimatorController.Core |
Serialized layer weight, AvatarMask, and additive toggle |
Used by CustomAnimController and PlayableAnimGraph |
AnimSetAsset |
PlayablesAnimatorController.Core |
ScriptableObject mapping case-sensitive keys to AnimClipEntry records |
AnimSetAsset |
AnimStateMachine |
PlayablesAnimatorController.States |
Pure C# state machine driving one IAnimationDriver layer with prioritized rules and auto-return |
AnimStateMachine |
IAnimTransitionRule |
PlayablesAnimatorController.States |
Pluggable transition predicate evaluated against AnimPlaybackState ("*" for any-state rules) |
FuncAnimTransitionRule |
Import 2D & 3D Quick Start (Samples~/QuickStart) from the Package Manager Samples tab:
Sample2DCodeAnimator: 2D sprite animation controller usingAnimStateMachineon layer0withfadeDuration: 0ffor instant switches acrossIdle,Run,Jump(priority5), andAttack(priority10,autoReturnStateId: "Idle").Sample3DLayeredAnimator: 3D layered controller demonstrating0.15flocomotion cross-fades on layer0, a priority-10upper-body slash on layer1with anAnimClipEventat0.45normalized time, andStopLayer(1, fadeOutDuration: 0.12f)on completion.
The package includes EditMode NUnit tests under Tests/Editor/ runnable from Window > General > Test Runner (EditMode tab):
Tests/Editor/PlayableAnimGraphTests.cs: verifiesPlayableAnimGraphinmanualUpdateMode: trueacross clip playback, cross-fade blending, priority blocking while a higher-priority clip is active, normalized-timeAnimClipEventinvocation, non-loopingonCompleteexecution, and priority lock release after completion.Tests/Editor/AnimStateMachineTests.cs: verifiesAnimStateMachineagainst a fakeIAnimationDriverfor state registration, predicate transitions, priority lockout during high-priority states, andAutoReturnStateIdtransition when a clip finishes.
- Leave the
AnimatorController slot empty:CustomAnimControllerbinds its ownPlayableGraphdirectly to theAnimator. Assigning a separateRuntimeAnimatorControlleron the sameAnimatoris unnecessary and can produce unexpected evaluation behavior. - Foot IK and Playable IK are disabled on created playables:
PlayableAnimGraph.PlaycallsSetApplyFootIK(false)andSetApplyPlayableIK(false)on eachAnimationClipPlayable. - Non-looping completion requires
AnimationClip.isLooping == false:OnComplete,OnClipCompleted,HasCompleted,AutoReturnStateId, and automatic priority release only trigger whenclip.isLoopingisfalseandclip.length > 1e-5f. Looping clips wrapNormalizedTimeand incrementLoopCountinstead. - Negative playback speed does not trigger events or completion:
FireClipEventsInRangetestsmarker >= prevNorm && marker <= currNorm, and completion checkstime >= length. Reversed clips (Speed < 0) will not fireAnimClipEventmarkers or complete automatically. - Playing on a muted layer restores layer weight to
1: WhenLayerWeight <= 0.001f(for example afterStopLayeror when initialized withdefaultWeight = 0), callingPlayon that layer cancels any active layer fade-out and sets its weight to1f. - Dynamically expanded layers have no
AvatarMaskor additive setting: CallingPlaywith aLayerindex beyond the configuredlayerslist expands theAnimationLayerMixerPlayableautomatically, but dynamically added layers use full-body override blending. Configure masked or additive layers up front inCustomAnimControlleror vialayerConfigsinPlayableAnimGraph. - Stopping layer
0vs. overlay layers: ImmediateStopLayer(layer, 0f)clears playables on any layer, but only resetsLayerWeightto0whenlayer > 0. Passing a positivefadeOutDurationfadesLayerWeightto0before clearing playables on any layer, including layer0. AnimSetAssetlookup keys are case-sensitive and cached by count:AnimSetAsset.TryGetEntryusesStringComparer.Ordinaland keeps the first valid entry if duplicate keys exist. In Play Mode, mutating existing keys inentrieswithout changingentries.Countdoes not invalidate the cached dictionary.