unity-animation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Unity Animation (Animator / Mecanim)

Unity 动画(Animator / Mecanim)

Control animation state with Unity 6's
Animator
and Animator Controllers: parameters, transitions, blend trees, layers, and humanoid IK. Targets Unity 6 (6000.0 LTS).
使用Unity 6的
Animator
和Animator Controller控制动画状态:参数、过渡、混合树、图层和人形IK。适用于**Unity 6 (6000.0 LTS)**版本。

When to use

适用场景

  • Use when connecting animation clips into a state machine, driving them from script via parameters, blending locomotion (idle→walk→run), layering an upper-body action over movement, or adding foot/hand IK on a humanoid rig.
  • Use when the project has
    *.controller
    (Animator Controller) and
    *.anim
    assets, or a rigged model with an Avatar.
When not to use: simple non-skeletal value tweens (UI fades, position lerps) are better done with a tween/coroutine — see
unity-csharp-scripting
. Timeline cutscenes are a separate tool. 2D sprite frame animation also uses the Animator but with sprite keyframes.
  • 适用于将动画片段连接到状态机、通过脚本参数驱动动画、混合 locomotion(idle→walk→run)、在移动动作上层叠加上身动作,或在人形骨骼上添加脚/手IK的场景。
  • 适用于项目包含
    *.controller
    (Animator Controller)和
    *.anim
    资源,或带有Avatar的绑定模型的场景。
不适用场景:简单的非骨骼属性补间(UI淡入淡出、位置 lerp)更适合用补间/协程实现——详见
unity-csharp-scripting
。Timeline过场动画是独立工具。2D精灵帧动画也使用Animator,但采用精灵关键帧。

Core workflow

核心工作流程

  1. Add an
    Animator
    to the model and assign an Animator Controller; for a humanoid model, set its rig to Humanoid so it has an Avatar (enables retargeting and IK).
  2. Define parameters on the controller —
    Float
    (Speed),
    Bool
    (IsGrounded),
    Int
    ,
    Trigger
    (Jump) — and states with transitions whose conditions read those parameters.
  3. Set parameters from script, never poke states directly:
    SetFloat
    ,
    SetBool
    ,
    SetInteger
    ,
    SetTrigger
    . The state machine resolves transitions for you.
  4. Blend continuous motion with a Blend Tree (one
    Float
    like Speed drives idle↔walk↔run) instead of many discrete states + transitions.
  5. Layer additive/override motion (e.g. an upper-body "aim" layer with an Avatar Mask) and control its
    layerWeight
    .
  6. Verify in the Animator window during Play mode — the live state highlights and parameter values update, so you can see exactly which transition fired (or didn't).
  1. 为模型添加
    Animator
    组件
    并分配Animator Controller;对于人形模型,将其骨骼设置为Humanoid以生成Avatar(支持重定向和IK)。
  2. 在控制器上定义参数——
    Float
    (Speed)、
    Bool
    (IsGrounded)、
    Int
    Trigger
    (Jump)——并创建带有过渡条件的状态,这些条件会读取这些参数。
  3. 通过脚本设置参数,切勿直接操作状态:使用
    SetFloat
    SetBool
    SetInteger
    SetTrigger
    。状态机会自动处理过渡逻辑。
  4. 使用混合树(Blend Tree)混合连续动作(一个
    Float
    参数如Speed驱动idle↔walk↔run),替代大量离散状态和过渡。
  5. 叠加/覆盖动画层(例如带有Avatar Mask的上身“瞄准”层)并控制其
    layerWeight
  6. 在Play模式下的Animator窗口验证——实时状态会高亮显示,参数值会更新,你可以清晰看到哪个过渡被触发(或未触发)。

Patterns

模式示例

1. Drive locomotion + a one-shot action from script

1. 通过脚本驱动 locomotion + 一次性动作

csharp
using UnityEngine;

[RequireComponent(typeof(Animator))]
public class CharacterAnim : MonoBehaviour
{
    private Animator _anim;
    // Cache parameter hashes — faster and typo-proof vs string lookups every frame.
    private static readonly int Speed     = Animator.StringToHash("Speed");
    private static readonly int IsGrounded= Animator.StringToHash("IsGrounded");
    private static readonly int Jump      = Animator.StringToHash("Jump");

    private void Awake() => _anim = GetComponent<Animator>();

    public void Tick(float planarSpeed, bool grounded)
    {
        _anim.SetFloat(Speed, planarSpeed);     // drives a 1D blend tree (idle/walk/run)
        _anim.SetBool(IsGrounded, grounded);    // gates a falling/landing transition
    }

    public void DoJump() => _anim.SetTrigger(Jump);  // fire-and-forget; auto-resets after use
}
csharp
using UnityEngine;

[RequireComponent(typeof(Animator))]
public class CharacterAnim : MonoBehaviour
{
    private Animator _anim;
    // 缓存参数哈希——比每次帧都进行字符串查找更快且避免拼写错误。
    private static readonly int Speed     = Animator.StringToHash("Speed");
    private static readonly int IsGrounded= Animator.StringToHash("IsGrounded");
    private static readonly int Jump      = Animator.StringToHash("Jump");

    private void Awake() => _anim = GetComponent<Animator>();

    public void Tick(float planarSpeed, bool grounded)
    {
        _anim.SetFloat(Speed, planarSpeed);     // 驱动1D混合树(idle/walk/run)
        _anim.SetBool(IsGrounded, grounded);    // 控制下落/着陆过渡
    }

    public void DoJump() => _anim.SetTrigger(Jump);  // 触发后自动重置,无需手动清理
}

2. Smooth a noisy input into a blend parameter

2. 将嘈杂输入平滑为混合参数

csharp
// dampTime smooths Speed so the blend tree doesn't snap; great for analog sticks.
_anim.SetFloat(Speed, targetSpeed, 0.1f /* dampTime */, Time.deltaTime);
csharp
// dampTime用于平滑Speed参数,避免混合树突变;非常适合模拟摇杆输入。
_anim.SetFloat(Speed, targetSpeed, 0.1f /* dampTime */, Time.deltaTime);

3. Play / cross-fade a state directly (bypassing parameter conditions)

3. 直接播放/交叉淡入状态(绕过参数条件)

csharp
// Useful for hit reactions where you want an immediate, explicit transition.
_anim.CrossFade("Hit", 0.1f);                    // blend over 0.1s normalized
// Or jump instantly:  _anim.Play("Hit");
csharp
// 适用于需要立即、明确过渡的受击反应场景。
_anim.CrossFade("Hit", 0.1f);                    // 在0.1秒内完成混合(归一化时间)
// 或者立即跳转: _anim.Play("Hit");

4. Wait until the current state finishes

4. 等待当前状态结束

csharp
private System.Collections.IEnumerator AfterAttack()
{
    var info = _anim.GetCurrentAnimatorStateInfo(0);   // layer 0
    yield return new WaitForSeconds(info.length);      // approximate clip length
    // ...follow-up logic
}
csharp
private System.Collections.IEnumerator AfterAttack()
{
    var info = _anim.GetCurrentAnimatorStateInfo(0);   // 第0层
    yield return new WaitForSeconds(info.length);      // 近似片段时长
    // ...后续逻辑
}

Pitfalls

常见陷阱

  • SetTrigger
    missed or "sticks"
    — triggers are consumed by the next satisfied transition and auto-reset; if no transition consumes it, it can fire later unexpectedly. Use
    ResetTrigger
    to clear, or prefer a
    Bool
    when the condition is a sustained state.
  • String parameter typos fail silently — a misspelled name just does nothing. Use
    Animator.StringToHash
    and cache the int hashes.
  • Transition feels laggy
    Has Exit Time
    makes the transition wait for the clip to reach a normalized time. Uncheck it for responsive, condition-driven transitions (jump, hit).
  • Character slides or won't move
    Apply Root Motion
    is on but your code also moves the transform (or vice versa). Decide: root motion or scripted movement, not both.
  • Upper-body layer overrides the whole body — set the layer's Blend mode (Override vs Additive), assign an Avatar Mask, and tune
    layerWeight
    (0–1).
  • IK does nothing — IK only applies inside
    OnAnimatorIK
    , requires "IK Pass" enabled on the layer, and needs a Humanoid Avatar.
  • SetTrigger
    未触发或“卡住”
    ——触发器会被下一个满足条件的过渡消耗并自动重置;如果没有过渡消耗它,可能会在之后意外触发。使用
    ResetTrigger
    清除,或者当条件是持续状态时优先使用
    Bool
    参数。
  • 参数字符串拼写错误无提示——拼写错误的名称不会产生任何效果。使用
    Animator.StringToHash
    并缓存整数哈希值。
  • 过渡感觉延迟——
    Has Exit Time
    会让过渡等待片段到达归一化时间点。对于响应式、条件驱动的过渡(跳跃、受击),请取消勾选此选项。
  • 角色滑动或无法移动——
    Apply Root Motion
    已启用,但你的代码也在移动transform(反之亦然)。选择其一:要么使用根运动,要么使用脚本控制移动,不要同时使用。
  • 上身层覆盖了整个身体——设置图层的混合模式(Override vs Additive),分配Avatar Mask,并调整
    layerWeight
    (0–1)。
  • IK无效果——IK仅在
    OnAnimatorIK
    中生效,需要在图层上启用“IK Pass”,并且需要人形Avatar。

References

参考资料

  • For blend trees (1D vs 2D Freeform/Directional), animation layers + Avatar Masks, and humanoid IK (
    OnAnimatorIK
    ,
    SetIKPositionWeight
    ,
    SetIKPosition
    , look-at), read
    references/blend-trees-and-ik.md
    .
  • Primary docs: Unity Manual "Animation" section and
    ScriptReference/Animator
    .
  • 关于混合树(1D vs 2D自由/方向型)、动画层 + Avatar Mask人形IK
    OnAnimatorIK
    SetIKPositionWeight
    SetIKPosition
    、看向目标),请阅读
    references/blend-trees-and-ik.md
  • 主要文档:Unity手册“Animation”章节和
    ScriptReference/Animator

Related skills

相关技能

  • unity-csharp-scripting
    — the MonoBehaviour and coroutine timing used above.
  • unity-physics
    — moving the body that the animation visualises.
  • game-ai
    — deciding when to play which animation state.
  • unity-csharp-scripting
    ——上述示例中使用的MonoBehaviour和协程计时。
  • unity-physics
    ——动画所可视化的角色身体移动。
  • game-ai
    ——决定何时播放何种动画状态。