Логотип Unity Animation

Unity Animation

Организация
Nice-Wolf-Studio
unity-animation

Unity 6 animation system guide. Use when working with Animator Controllers, animation state machines, blend trees, animation clips, Avatar system, humanoid rigs, root motion, animation events, Timeline, or Cinemachine. Based on Unity 6.3 LTS documentation.

Обзор

ИздательNice-Wolf-Studio
Репозиторийunity-claude-skills
Название навыкаunity-animation
Звёзды
40
Форки
5
Встроенные файлы
3
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Файл SKILL.md, который модель загружает по необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 3

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Опубликовано на GitHub: Nice-Wolf-Studio. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Unity Animation в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-animation
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Nice-Wolf-Studio/unity-claude-skills.git /tmp/unity-claude-skills
mkdir -p .claude/skills
cp -r /tmp/unity-claude-skills/skills/unity-animation .claude/skills/unity-animation
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Unity Animation в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Unity Animation, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Unity Animation не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими API-ключами.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Unity Animation System

Animation System Overview

Unity's Mecanim animation system is built on three interconnected components:

  1. Animation Clips -- Unit pieces of motion (Idle, Walk, Run)
  2. Animator Controller -- State machine organizing clips into a flowchart of states and transitions
  3. Avatar System -- Maps humanoid character skeletons to a common internal format for retargeting

The Animator component is attached to GameObjects and references both the Animator Controller and Avatar assets needed for playback.

Animation Types

  • Humanoid -- Requires Avatar configuration; supports retargeting between different character rigs; 15-20% more CPU-intensive than Generic
  • Generic -- Animates Transform or MonoBehaviour properties on specific hierarchies; not transferable between different hierarchies
  • Legacy -- Older Animation component; use for simple single-shot or UI animations

Animator Controller

An Animator Controller asset arranges Animation Clips and Transitions for a character or animated GameObject.

Creating: Right-click in Project window > Create > Animator Controller

Key Components

  • States -- Each state plays an associated Animation Clip or Blend Tree
  • Transitions -- Define how and when the state machine switches between states
  • Parameters -- Variables (Float, Int, Bool, Trigger) that scripts set to control transitions
  • Layers -- Separate state machines for different body parts or animation concerns
  • Sub-State Machines -- Nested state machines for hierarchical organization

Parameters

Four types are available:

TypeDescriptionScript Method
FloatDecimal numberSetFloat() / GetFloat()
IntWhole numberSetInteger() / GetInteger()
BoolTrue/falseSetBool() / GetBool()
TriggerAuto-resetting boolSetTrigger() / ResetTrigger()
csharp
using UnityEngine;

public class PlayerAnimController : MonoBehaviour
{
    Animator animator;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        // Note: Uses legacy Input Manager for simplicity. See unity-input for the new Input System.
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        bool fire = Input.GetButtonDown("Fire1");

        animator.SetFloat("Forward", v);
        animator.SetFloat("Strafe", h);
        animator.SetBool("Fire", fire);
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.CompareTag("Enemy"))
        {
            animator.SetTrigger("Die");
        }
    }
}

Animator Override Controller

Replaces animation clips in an Animator Controller while keeping structure, parameters, and logic intact. Useful for multiple characters sharing the same state machine but using different clips.

Critical: Set transition exit times in normalized time (not seconds) when using Override Controllers, or exit times may be ignored if override clips have different durations.

Layers

  • Override mode -- Replaces animation from previous layers
  • Additive mode -- Adds animation on top of previous layers
  • Avatar Mask -- Restricts a layer to specific body parts (e.g., upper body only)
  • Synced Layers -- Reuse state machine structure with different clips

State Machines and Transitions

States

Each state in the Animator Controller represents a distinct action. Special states include:

  • Entry -- Default entry point
  • Any State -- Transitions from any current state
  • Exit -- Exits the current state machine or sub-state machine

Transitions

Transitions define how states blend into each other.

SettingDescription
Has Exit TimeTransition triggers at a normalized time (e.g., 0.75 = 75% complete)
Transition DurationBlend period; in seconds (Fixed Duration) or fraction of source state
Transition OffsetWhere destination state begins playback (0.5 = midpoint)
ConditionsParameter-based rules; all must be satisfied simultaneously
Interruption SourceWhich transitions can interrupt: None, Current State, Next State, or combinations
Ordered InterruptionWhether transition parsing stops at current transition or any valid one

When both Has Exit Time and Conditions are set, Unity only checks conditions after the exit time.

State Machine Behaviours

Scripts inheriting StateMachineBehaviour attach to states. Callbacks: OnStateEnter, OnStateUpdate, OnStateExit, OnStateMove, OnStateIK. All receive (Animator animator, AnimatorStateInfo stateInfo, int layerIndex).

csharp
public class AttackState : StateMachineBehaviour
{
    public AudioClip attackSound;
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        AudioSource.PlayClipAtPoint(attackSound, animator.transform.position);
    }
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        // Cleanup when leaving state
    }
}

Blend Trees

Blend Trees smoothly blend between multiple similar animations based on parameter values, unlike transitions which switch between distinct states over time.

Critical requirement: Animations must be of similar nature and timing. Foot contact points should align in normalized time (e.g., left foot at 0.0, right foot at 0.5).

Blend Types

  • 1D -- Single parameter controls blending (e.g., speed for walk/run)
  • 2D Simple Directional -- Two parameters, one motion per direction
  • 2D Freeform Directional -- Two parameters, multiple motions per direction
  • 2D Freeform Cartesian -- Two parameters, motions not representing directions
  • Direct -- Each motion has its own weight parameter (facial animations)

Creating: Right-click in Animator Controller > Create State > From New Blend Tree. Double-click to enter the graph. Add child motions via the Inspector.

csharp
// Driving a locomotion blend tree from script
void Update()
{
    float speed = new Vector3(rb.velocity.x, 0, rb.velocity.z).magnitude;
    float direction = Vector3.SignedAngle(transform.forward,
        rb.velocity.normalized, Vector3.up);

    animator.SetFloat("Speed", speed, 0.1f, Time.deltaTime);
    animator.SetFloat("Direction", direction, 0.1f, Time.deltaTime);
}

Avatar and Humanoid Rigs

The Avatar system identifies models as humanoid and maps body parts for animation retargeting.

Key Concepts

  • Avatar -- Maps bone structure to Unity's internal humanoid format
  • Retargeting -- Animations transfer between different humanoid rigs sharing the same Avatar mapping
  • Muscle Definitions -- Intuitive control in muscle space rather than bone space

Setup

  1. Select model in Project window
  2. In Rig tab of Import Settings, set Animation Type to Humanoid
  3. Configure Avatar mapping (Unity auto-maps when possible)
  4. Verify and adjust bone assignments in the Avatar Configuration window

Root Motion

Root motion transfers animation-driven movement to the GameObject's Transform.

Architecture

  • Body Transform -- Character's center of mass; stores world-space curves
  • Root Transform -- Y-plane projection of Body Transform; computed at runtime each frame

Clip Inspector Settings

SettingPurpose
Bake Into Pose (Rotation)Orientation stays on body; GameObject receives no rotation
Bake Into Pose (Y)Vertical motion stays on body; enable for all except jumps
Bake Into Pose (XZ)Horizontal motion stays on body; enable for idle clips to prevent drift
Based UponBody Orientation (mocap), Original (keyframed), Feet (prevents floating)

Animator.gravityWeight is driven by Bake Into Pose Position Y: enabled = 1, disabled = 0.

csharp
// Custom root motion handling
using UnityEngine;

[RequireComponent(typeof(Animator))]
public class RootMotionController : MonoBehaviour
{
    Animator animator;
    CharacterController controller;

    void Start()
    {
        animator = GetComponent<Animator>();
        controller = GetComponent<CharacterController>();
        animator.applyRootMotion = false; // We handle it manually
    }

    void OnAnimatorMove()
    {
        // Apply root motion through CharacterController
        Vector3 deltaPosition = animator.deltaPosition;
        deltaPosition.y -= 9.81f * Time.deltaTime; // Add gravity
        controller.Move(deltaPosition);
        transform.rotation *= animator.deltaRotation;
    }
}

Animation Events

Animation events trigger functions at designated points in the animation timeline.

Parameter Types

  • Float -- Numeric values (e.g., volume)
  • Int -- Integer values
  • String -- Text data
  • Object -- GameObject or Prefab references

Setup

  1. In Animation tab, expand Events section
  2. Position playback head on desired frame
  3. Click Add Event
  4. Set Function name matching a method on an attached script
csharp
using UnityEngine;

public class FootstepHandler : MonoBehaviour
{
    public AudioClip[] footstepSounds;
    public GameObject dustPrefab;

    // Called by animation event -- function name must match event
    public void PlayFootstep(int footIndex)
    {
        if (footstepSounds.Length > 0)
        {
            int clipIndex = Random.Range(0, footstepSounds.Length);
            AudioSource.PlayClipAtPoint(footstepSounds[clipIndex], transform.position);
        }
    }

    // Called by animation event passing an Object parameter
    public void SpawnEffect(Object effectPrefab)
    {
        Instantiate((GameObject)effectPrefab, transform.position, Quaternion.identity);
    }
}

Timeline

Timeline creates cinematic content, gameplay sequences, audio sequences, and particle effects. Package: com.unity.timeline (v1.8.11, Unity 6.3 compatible).

Core Components

  • Timeline Asset -- Defines tracks, clips, and their arrangement
  • Timeline Instance -- Runtime instance bound to specific scene objects
  • Playable Director -- Component that plays Timeline assets and binds tracks to scene objects

Track Types

TrackPurpose
AnimationControls Animator on bound GameObject
AudioPlays AudioClips on bound AudioSource
ActivationEnables/disables bound GameObject
SignalFires events at specific times via SignalReceiver
ControlTriggers sub-Timelines, particle systems, or other Playable Directors
PlayableCustom track using Playables API

Features

  • Animation recording directly in Timeline
  • Humanoid animation support
  • Animation Override tracks
  • Sub-Timelines for modular composition

Scripting Animation

Inverse Kinematics (IK)

Requires: Humanoid Avatar, IK Pass enabled on layer.

csharp
using UnityEngine;

public class IKController : MonoBehaviour
{
    Animator animator;
    public bool ikActive = true;
    public Transform rightHandTarget;
    public Transform lookTarget;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void OnAnimatorIK()
    {
        if (animator == null || !ikActive) return;

        // Look at target
        animator.SetLookAtWeight(1f);
        animator.SetLookAtPosition(lookTarget.position);

        // Right hand IK
        animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1f);
        animator.SetIKRotationWeight(AvatarIKGoal.RightHand, 1f);
        animator.SetIKPosition(AvatarIKGoal.RightHand, rightHandTarget.position);
        animator.SetIKRotation(AvatarIKGoal.RightHand, rightHandTarget.rotation);
    }
}

Direct State Playback

csharp
// Play state immediately
animator.Play("Attack");

// Play with normalized time offset (start at 50%)
animator.Play("Attack", 0, 0.5f);

// Crossfade into state over 0.25 seconds
animator.CrossFadeInFixedTime("Run", 0.25f);

// Crossfade using normalized time
animator.CrossFade("Run", 0.1f);

Querying State Information

csharp
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);

if (stateInfo.IsName("Attack"))
{
    Debug.Log("Currently attacking");
}

if (stateInfo.normalizedTime >= 1.0f && !animator.IsInTransition(0))
{
    Debug.Log("Animation finished");
}

// Use hash for performance
int runHash = Animator.StringToHash("Run");
if (animator.HasState(0, runHash))
{
    animator.Play(runHash);
}

Target Matching

csharp
// Match character's hand to a ledge position during climb animation
animator.MatchTarget(ledgePosition, Quaternion.identity, AvatarTarget.RightHand,
    new MatchTargetWeightMask(Vector3.one, 0f), 0.1f, 0.4f);

Common Patterns

Character Locomotion Controller

csharp
using UnityEngine;

[RequireComponent(typeof(Animator))]
public class LocomotionController : MonoBehaviour
{
    Animator animator;
    static readonly int SpeedHash = Animator.StringToHash("Speed");
    static readonly int GroundedHash = Animator.StringToHash("Grounded");
    static readonly int JumpHash = Animator.StringToHash("Jump");

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        float speed = Input.GetAxis("Vertical");
        animator.SetFloat(SpeedHash, Mathf.Abs(speed), 0.1f, Time.deltaTime);
        animator.SetBool(GroundedHash, IsGrounded());

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            animator.SetTrigger(JumpHash);
        }
    }

    bool IsGrounded()
    {
        return Physics.Raycast(transform.position + Vector3.up * 0.1f, Vector3.down, 0.2f);
    }
}

Runtime Override Controller Swap

csharp
using UnityEngine;

public class WeaponAnimSwap : MonoBehaviour
{
    public AnimatorOverrideController swordOverride;
    public AnimatorOverrideController bowOverride;
    Animator animator;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    public void EquipSword()
    {
        animator.runtimeAnimatorController = swordOverride;
    }

    public void EquipBow()
    {
        animator.runtimeAnimatorController = bowOverride;
    }
}

Anti-Patterns

Anti-PatternProblemSolution
String parameters every frameGC allocation, slow lookupCache hashes with Animator.StringToHash()
Humanoid rig for non-humanoid objects15-20% unnecessary CPU overheadUse Generic animation type for props, animals, effects
Multiple Animators under shared rootSingle-thread write limitation per hierarchy blocks parallelismGive each Animator its own root GameObject
StateMachineBehaviour overuseCreates synchronization points, breaks parallel evaluationMinimize SMB callbacks; prefer script-side logic
RectTransform animation via AnimatorDeterministic write issuesUse legacy Animation component for UI animation
Complex state machines for single-shot animsContinuous transition evaluation even at idleUse Animation component or Playables API instead
Calling Animator.Update() manuallyBypasses parallel executionUse PlayableGraph for manual control with parallelism
Not setting transition exit time to normalizedOverride Controller clips may skip transitionsAlways use normalized time for exit times
Forgetting Rebind() after controller swapStale bindings cause incorrect playbackCall Rebind() when changing controllers at runtime
Bake Into Pose disabled on idle clips (XZ)Drift accumulation on idle animationsEnable Bake Into Pose XZ for stationary clips

Key API Quick Reference

Animator -- Essential Properties

applyRootMotion, speed, updateMode (Normal/AnimatePhysics/UnscaledTime), cullingMode, deltaPosition, deltaRotation, velocity, isHuman, layerCount, bodyPosition, gravityWeight

Animator -- Essential Methods

  • Playback: Play(state, layer, time), CrossFade(state, duration), CrossFadeInFixedTime(state, duration)
  • Parameters: SetFloat/Int/Bool/Trigger(name, value), GetFloat/Int/Bool(name), ResetTrigger(name)
  • State Query: GetCurrentAnimatorStateInfo(layer), GetNextAnimatorStateInfo(layer), IsInTransition(layer)
  • IK: SetIKPosition/Rotation(goal, value), SetIKPositionWeight/RotationWeight(goal, weight), SetLookAtPosition(pos)
  • Utility: MatchTarget(...), GetBoneTransform(bone), Rebind(), StringToHash(name), SetLayerWeight(layer, weight)

Related Skills

  • unity-foundations -- Core Unity concepts, GameObjects, Components, project structure
  • unity-scripting -- MonoBehaviour lifecycle, C# patterns, event systems
  • unity-graphics -- Rendering, materials, shaders (relevant for animated material properties)

Additional Resources

Встроенные файлы

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Unity Animation?

Unity 6 animation system guide. Use when working with Animator Controllers, animation state machines, blend trees, animation clips, Avatar system, humanoid rigs, root motion, animation events, Timeline, or Cinemachine. Based on Unity 6.3 LTS documentation.

Зачем использовать Unity Animation в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Unity Animation — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Unity Animation в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-animation. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Unity Animation?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Unity Animation?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Unity Animation: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Unity Animation?

Да. Навык опубликован на GitHub автором Nice-Wolf-Studio по лицензии MIT. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это многоразовый набор инструкций, который объясняет модели ИИ, как выполнять конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты для вызова — код, который где-то выполняется и возвращает результат. Навык ИИ вместо этого даёт модели знания и порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇