Course contentsShow
← Unity Game Development
Lesson 531 of 8288. Artificial IntelligenceFree lesson

Applying Decorators for Flow Control

You will use decorators to wrap nodes with logic that controls execution frequency, success conditions, or interruption capabilities during runtime.

In this lesson, you will learn how to use Decorator nodes to dynamically wrap your Behavior Tree nodes, allowing you to intercept execution and modify their flow without altering the underlying logic.

The Concept of Decorators

In a Behavior Tree, nodes typically perform a specific action (Leaf) or manage branches (Composite). A Decorator acts as a "middle-man"—it sits above a single child node to inspect, limit, or modify the child's output. Think of it as a logical filter that decides if or how many times a node should run.

For instance, you might want an AI to play a "Patrol" animation, but only if the AI is currently on the ground. Instead of hardcoding that check inside your Patrol node, you wrap it in a ConditionDecorator. If the condition fails, the Decorator intercepts the request, preventing the Patrol node from even executing.

Common Flow Control Patterns

Decorators are most powerful when managing execution frequency or success state:

  • Inverter: Flips the result. If the child node fails (e.g., "Is Player Near?"), the Inverter returns success, allowing the tree to proceed.
  • Repeater: Forces a node to run multiple times, which is perfect for looping sequences or ensuring a task completes.
  • Cooldown: A time-based gatekeeper that prevents a node from running again until a set duration has passed.

Implementation Example

Consider a Repeater decorator wrapping an action node:

public class RepeaterDecorator : DecoratorNode {
    private int _repeatCount;
    
    public override NodeState Evaluate() {
        for (int i = 0; i < _repeatCount; i++) {
            child.Evaluate();
        }
        return NodeState.Success;
    }
}

By decoupling flow control from the action logic, your Behavior Tree remains modular. If you decide the AI should only perform an action every 5 seconds instead of every frame, you simply wrap the action in a CooldownDecorator rather than rewriting the action class itself. This architecture keeps your AI behaviors clean, scalable, and highly reusable across different NPCs.

Key Takeaway: Decorators provide a non-intrusive way to inject flow control logic like looping, inverting, or timing, allowing you to extend node behavior without bloating your leaf node classes.