Course contentsShow
← Unity Game Development
Lesson 382 of 8286. Animation and CinemachineFree lesson

Organizing Animations with Nested Sub-State Machines

Structure complex character behaviors by grouping related animations into sub-state machines to keep the Animator graph clean and manageable.

In this lesson, you will learn how to clean up your Animator Controller by grouping related animation states into nested sub-state machines.

Why Use Sub-State Machines?

As you build more complex characters, your Animator window can quickly become a "spaghetti" web of lines and boxes. When a state machine grows too large, it becomes difficult to manage, prone to bugs, and overwhelming to look at. A Sub-State Machine acts like a folder for your states, allowing you to encapsulate specific behaviors—like "Locomotion," "Combat," or "Death"—into a single, collapsible node.

Creating a Sub-State Machine

To create one, right-click in the Animator graph and select Create State Machine. It will appear as a block with a specialized icon representing a stack of nodes. You can double-click this block to "enter" it, opening a fresh, empty workspace where you can define its internal states and transitions.

For example, imagine a character with five different melee attacks. Instead of having five separate states cluttering your main graph, you can group them into a "MeleeAttack" sub-state machine. Your main graph only needs to know about the "MeleeAttack" entry point, keeping the primary logic flow clean.

Workflow Example

When you are inside a sub-state machine, you can create an Entry point and an Exit node. These act as bridges to your main graph:

  • Entry: Any transition pointing to the sub-state machine will arrive here first.
  • Exit: Any transition pointing from a state inside the machine to its "Exit" node will return the logic to the main graph.

By using these, you can treat a group of animations as a single, modular function. When you return to the parent layer, you only see one icon, which drastically simplifies debugging and prevents "line crossing" issues that often occur with complex state machines.

// Example: Triggering an attack state machine from code
animator.SetTrigger("EnterCombatState"); 
// The logic inside the sub-state machine handles the specific attack variations.

Key Takeaway: Nested sub-state machines allow you to collapse complex groups of animations into single nodes, turning an unmanageable mess of states into a clean, hierarchical, and professional Animator Controller.