Animation in games is not just about playing clips — it is about controlling, blending, modifying, and responding to animation through code. Every major game engine provides APIs for interacting with animation at runtime, from simple play/stop commands to complex procedural animation systems.
This guide covers animation scripting across Unreal Engine, Unity, and Godot, with practical patterns for controlling animation through code. Whether you are triggering a jump animation from a button press, blending combat stances based on weapon type, or building a procedural locomotion system, this is where animation meets programming.
A well-designed animation API decouples playback logic from gameplay code, giving programmers clean hooks into the animation state machine without needing to reach into animator-controlled parameters directly.
Unreal Engine: Animation Blueprints and C++ Animation
Unreal Engine uses Animation Blueprints as its primary animation scripting system. An Animation Blueprint is a specialized Blueprint class that runs every frame on a skeletal mesh, evaluating an animation graph to produce the final pose.
Animation Blueprint Structure
Every Animation Blueprint has two graphs: the Event Graph, which reads gameplay variables and computes animation parameters, and the Anim Graph, which uses those parameters to evaluate animation nodes (state machines, blend spaces, montages).
In the Event Graph, you typically read the character's velocity, direction, and state flags (is jumping, is crouching, is aiming), then store them in variables that the Anim Graph reads. The Anim Graph uses these variables as inputs to state machine transitions and blend space parameters.
C++ Animation Integration
For performance-critical animation logic, Unreal supports C++ animation classes. Create a class inheriting from UAnimInstance and override NativeUpdateAnimation to compute animation parameters in C++ instead of Blueprint. This is significantly faster for complex calculations and allows you to access engine systems that are not exposed to Blueprint.
The C++ UAnimInstance class can be used as the parent class for an Animation Blueprint, giving you the best of both worlds — performance-critical logic in C++, visual animation graph editing in Blueprint.
Unity: Animator Controller Scripting
Unity's animation system centers on the Animator Controller, a state machine asset that defines states, transitions, and parameters. You control it from code through the Animator component.
Setting Parameters
The primary way to drive animation in Unity is by setting Animator parameters from script. Parameters come in four types: Float (for blend trees), Int (for indexed selection), Bool (for state conditions), and Trigger (for one-shot transitions).
Use animator.SetFloat("Speed", currentSpeed) to drive a locomotion blend tree. Use animator.SetTrigger("Jump") to trigger a jump animation. Use animator.SetBool("IsGrounded", isGrounded) to control landing transitions. These calls are the bread and butter of Unity animation scripting.
Direct State Control
When parameters are not enough, Unity provides direct state control through Animator.Play("StateName") and Animator.CrossFade("StateName", transitionDuration). These bypass the state machine's transition rules and force the Animator into a specific state. Use them sparingly — they break the state machine flow and can cause unexpected behavior if overused.
Godot: AnimationPlayer and AnimationTree
Godot provides two animation nodes: AnimationPlayer for direct clip playback and AnimationTree for complex blend systems.
AnimationPlayer
The AnimationPlayer is straightforward: call animation_player.play("walk") to play an animation, stop() to stop, queue("run") to queue the next clip. It supports blending via play("run", 0.3), where the second parameter is the blend time. For simple games, AnimationPlayer is often sufficient without needing AnimationTree at all.
AnimationTree
For complex character animation, Godot's AnimationTree provides blend trees, state machines, and transition nodes similar to Unity's Animator Controller. Drive it from GDScript by setting parameters: anim_tree.set("parameters/blend_position", velocity). The AnimationTree processes the blend graph each frame and outputs the final pose.
Playing Animations from Code
Regardless of engine, there are three main patterns for triggering animations from code:
Parameter-Driven (Recommended)
Set parameters that drive the animation state machine. The state machine handles transitions and blending automatically. This is the most maintainable approach because the animation logic (in the state machine) is decoupled from the gameplay logic (in code). Your code says "the character is moving at speed 3.5" and the animation system figures out which animation to play.
Direct Play
Call a play function with an animation name. This is simple but brittle — if the animation name changes, or if you need to handle transitions, you end up writing transition logic in code that should live in the animation system. Use this for UI animations, one-shot effects, and simple systems.
Montage/Action System
Play a special animation on top of the current animation graph without disrupting the underlying state. Unreal calls these Animation Montages. Unity achieves this with Override layers. This is the standard approach for attacks, emotes, hit reactions, and other gameplay actions that overlay the base locomotion.
Blending Animations Programmatically
Sometimes you need to control animation blending directly from code rather than through a blend tree asset. Common scenarios include procedurally blending between aim directions (upper body tracks a target while lower body follows locomotion), blending between animation sets based on equipment (heavy armor vs. light armor locomotion), and dynamically adjusting blend weights during gameplay events.
In Unreal, use Layered Blend per Bone nodes in the Anim Graph with bone weights driven by Blueprint variables. In Unity, use Animator layers with weight controlled via animator.SetLayerWeight(layerIndex, weight). In Godot, AnimationTree blend nodes expose weight parameters that can be set from code.
Animation Speed and Time Control
Controlling animation playback speed is essential for matching animation to gameplay. A walk animation might need to play at 80% speed when the character is moving slowly, or a hit reaction might need to play in slow motion during a dramatic moment.
In Unreal, use a Rate Scale node in the Anim Graph or set the play rate on a Montage. In Unity, use animator.speed for global speed or per-state speed multipliers. In Godot, use animation_player.playback_speed. All engines also support negative speed for reverse playback, which is useful for "un-drawing" a weapon or reversing a door animation.
Runtime Animation Modification
Advanced animation systems modify animation data at runtime. This includes additive animation (layering a breathing animation on top of any base pose), pose blending (blending toward a specific target pose based on a gameplay parameter), and curve-driven animation (reading animation curves to drive non-skeletal properties like material parameters or blend shape weights).
Additive animation is particularly powerful with MoCap data. Capture a subtle idle variation — a weight shift, a head look, a breathing pattern — and apply it additively on top of any base animation. This adds life and variety to characters without requiring unique full-body animations for every combination.
Procedural Animation from Code
Procedural animation generates motion from code rather than pre-authored clips. Common applications include look-at systems (the character's head and eyes track a point of interest), reach IK (a hand reaches for a door handle, adjusting based on the handle's position), leaning into turns (the character's upper body tilts based on movement direction and speed), and breathing simulation (subtle chest and shoulder movement driven by a sine wave).
Procedural animation typically runs as a post-process on top of the regular animation evaluation. The animation graph produces a base pose, then procedural systems modify specific bones. This layered approach lets you combine the natural quality of MoCap-driven base animation with the responsiveness of procedurally driven adjustments.
Animation Montage and Action System
Montages (Unreal) and action systems (generic term) allow you to play one-shot animations that overlay the base animation state without breaking the state machine flow. This is how most games handle attacks, abilities, emotes, and reactions.
In Unreal, create an Animation Montage from one or more animation sequences. Play it from code with PlayMontage. The montage plays on a specific slot, blending with the base pose. You can define sections within the montage for branching (combo attacks) and add notifies for gameplay events (damage windows, VFX triggers).
In Unity, use an Override layer on the Animator Controller. When you need to play an action, set the layer weight to 1 and trigger the animation. When it finishes, set the weight back to 0. This achieves the same overlay behavior as Unreal's montages.
State Machine Manipulation
While state machines are usually designed visually, there are cases where you need to inspect or modify state machine behavior from code. Reading the current state name (for UI or debugging), forcing a state transition (for gameplay events that override normal flow), querying transition progress (to sync gameplay events with animation transitions), and dynamically enabling or disabling transitions (to lock the character in a state during certain gameplay conditions).
In Unity, animator.GetCurrentAnimatorStateInfo(0) returns information about the current state, including its name hash and normalized time. In Unreal, the Animation Blueprint can access state machine data through the GetRelevantAnimTimeRemaining and related functions.
Animation Curve Access from Code
Animation curves store per-frame float values alongside the skeletal animation. They are used to drive non-skeletal properties: material blend weights (transitioning from dry to wet during a swimming animation), physics simulation intensity (reducing ragdoll influence during the controlled part of a fall animation), gameplay flags (an "IsVulnerable" curve that marks frames where the character can be interrupted), and audio parameters (controlling footstep volume based on the foot's velocity curve).
In Unreal, access curves through GetCurveValue("CurveName") on the AnimInstance. In Unity, add curves in the Animation window and read them via animation events or the Animator.GetFloat method if bound to a parameter.
IK Target Setting from Code
Inverse Kinematics (IK) adjusts bone chains to reach target positions. Setting IK targets from code enables foot placement on uneven terrain (cast rays from the feet, set IK targets at hit points), hand placement on objects (set hand IK target to a weapon grip or surface contact point), and head/eye tracking (set look-at target to a point of interest or another character).
In Unreal, use the Two Bone IK or FABRIK nodes in the Anim Graph with target positions driven by Blueprint variables. In Unity, implement OnAnimatorIK in a MonoBehaviour and call animator.SetIKPosition and animator.SetIKRotation to set targets for the built-in IK system.
Runtime Retargeting APIs
Runtime retargeting applies animation data from one skeleton to another in real time. This is useful for sharing animations across characters with different proportions, applying MoCap data captured on one performer to characters of different sizes, and user-customizable characters where proportions change at runtime.
Unreal Engine 5 provides the IK Retargeter system, which can be configured and triggered from code. Unity's Animation Rigging package enables runtime retargeting through constraint-based systems. MoCap data is ideal for retargeting because the source motion is physically grounded — retargeted results look natural even on characters with different proportions because the timing and weight of the original human performance carries through.
Best Practices for Animation-Code Integration
Keep animation and gameplay logic separated. Animation code should read state, not write it. The gameplay system decides the character is attacking — the animation system figures out which attack animation to play and how to blend it.
Use data-driven approaches wherever possible. Animation parameters, blend settings, and transition rules should be configurable in data assets, not hard-coded. This lets designers iterate without programmer involvement.
Cache component references. Calling GetComponent<Animator>() every frame is wasteful. Cache the reference in Start() or BeginPlay() and reuse it. Profile animation code regularly — animation evaluation is per-character, per-frame, and scales linearly with character count.
When working with MoCap animation packs like those from MoCap Online, the animation data quality simplifies your code. Clean, consistent data means fewer special cases, fewer workarounds, and more predictable behavior from your animation systems. Focus your scripting effort on gameplay integration rather than compensating for data quality issues.
FAQ
What is the best way to trigger animations from gameplay code?
Use the parameter-driven approach for ongoing states (locomotion, stance, aiming) and the montage/action pattern for one-shot events (attacks, emotes, reactions). Set parameters on the Animator or AnimInstance and let the animation state machine handle transitions. This keeps your gameplay code clean and your animation system flexible.
How do I play an animation without interrupting the current state machine?
Use Animation Montages in Unreal or Override layers in Unity. These play animations on top of the base state machine without disrupting its state. The montage blends in, plays the action animation, and blends back out, while the underlying locomotion state continues running underneath.
Can I modify animation clips at runtime?
Direct modification of animation clip data at runtime is generally not supported and not recommended. Instead, use additive animation, procedural post-processing, and IK systems to modify the final pose. These approaches achieve the same visual result — modifying how an animation looks when played — without altering the source data. This is more performant and avoids issues with shared animation assets.
How do I synchronize animation across networked multiplayer?
Replicate the animation parameters (speed, direction, state flags), not the raw animation data. Each client evaluates the animation graph locally using the replicated parameters. For one-shot actions like attacks, replicate a trigger event and let each client play the montage locally. This approach uses minimal bandwidth since you are sending a few float and boolean values rather than bone transforms.
Professional Animation Data for Your Scripting Pipeline
Animation scripting APIs are only as good as the animation data they control. MoCap Online provides professionally captured motion capture packs with consistent naming conventions, uniform skeletal hierarchies, and predictable frame timing — making them ideal for batch processing, automated retargeting scripts, and programmatic animation systems. Our clean data structure means your animation scripting code can reliably parse clip names, access bone transforms, and manipulate keyframe data without encountering inconsistencies between packs. Whether you're writing custom importers, building procedural animation layers in code, or automating your animation pipeline with Python or C++ scripts, starting with well-structured motion capture source data saves significant development time. Available in FBX, BIP, Unreal Engine, Unity, Blender, and iClone formats.
