Course contentsShow
← Unity Game Development
Lesson 469 of 8287. Advanced Game ArchitectureFree lesson

Designing Hierarchical State Structures

Organize states into parent-child relationships to share common behaviors and reduce code duplication across complex state machines.

In this lesson, you will learn how to reduce code duplication by nesting states into parent-child relationships, allowing child states to inherit common behaviors from their parents.

The Problem: Redundant Logic

In a flat state machine, if you have multiple "Combat" states—like MeleeAttack, RangedAttack, and Defend—each state often needs to handle the same logic, such as checking if the player is stunned or tracking the target's proximity. In a flat structure, you end up repeating these Update checks in every single class.

The Solution: Hierarchical States

Hierarchical State Machines (HSM) allow a "Parent" state to hold shared logic, while "Child" states focus only on what makes them unique. If a message or update arrives, it is processed by the child first; if the child doesn't handle it, it passes the request up to the parent.

Think of it like an inheritance tree for behavior:

  1. Base State: Handles global logic (e.g., gravity, stun checks).
  2. Combat State (Child of Base): Handles weapon switching and target tracking.
  3. Melee State (Child of Combat): Handles the specific animation and hit-box logic for a sword swing.

Implementation Concept

You can implement this by giving your base state class a reference to a ParentState.

public abstract class State {
    protected State parentState;

    public virtual void HandleInput() {
        // Allow the parent to handle input first, or act as a fallback
        parentState?.HandleInput();
    }
}

public class MeleeAttackState : State {
    public override void HandleInput() {
        // Child-specific logic here
        base.HandleInput(); // Optionally call the parent's logic
    }
}

By structuring your states this way, you ensure that if the "Combat" logic changes (e.g., adding a new way to track targets), you only update the CombatState once, and every child state—Melee, Ranged, and Magic—inherits that improvement automatically. This keeps your state machine modular and significantly easier to debug as your game grows in complexity.

Key Takeaway: Hierarchical states allow you to encapsulate shared behaviors in parent classes, eliminating redundancy and creating a clean, scalable architecture for complex game entities.