🔀 Blueprint Flow Control and Logic
Every game requires decision-making: "If the player has the key, open the door. If not, display a message." Flow control nodes are the building blocks of logical thinking in Blueprints—they let you create branches, loops, sequences, and complex decision trees. In this lesson, you'll master the tools that transform simple Blueprint scripts into intelligent, responsive gameplay systems that react appropriately to any situation.
🎯 Learning Objectives
By the end of this lesson, you will be able to:
- Use Branch nodes to create conditional logic (if/then/else)
- Implement Switch statements for multi-option decision-making
- Build loops with For, While, and ForEach nodes
- Control execution flow with Sequence, Delay, and Gate nodes
- Create complex boolean logic with AND, OR, NOT operations
- Use comparison operators to evaluate conditions
- Implement state machines for AI and gameplay logic
- Optimize flow control for performance
- Debug complex logic chains effectively
Estimated Time: 90-105 minutes
Prerequisites: Lesson 3.2 - Blueprint Communication and Variables
📑 In This Lesson
Flow Control Fundamentals
By default, Blueprint nodes execute in a straight line—left to right, one after another. But games need intelligence: make decisions, repeat actions, handle different scenarios. That's where flow control comes in.
📖 Key Concept
Flow Control: Mechanisms that determine which nodes execute and in what order based on conditions, loops, or explicit control. Flow control transforms linear scripts into dynamic, intelligent systems that respond differently depending on the situation. Without it, every Blueprint would do the exact same thing every time.
The Need for Flow Control
Consider a door Blueprint without flow control:
flowchart LR
A[Player Interacts] --> B[Play Opening Sound]
B --> C[Open Door]
C --> D[End]
style A fill:#4CAF50,stroke:#2e7d32,color:#fff
style B fill:#2196F3,stroke:#1565c0,color:#fff
style C fill:#2196F3,stroke:#1565c0,color:#fff
style D fill:#9e9e9e,stroke:#616161,color:#fff
Figure: Linear execution—always does the same thing, no intelligence.
This door always opens, even if it's already open, locked, or requires a key. Not smart!
Now with flow control:
flowchart TD
A[Player Interacts] --> B{Is Already Open?}
B -->|Yes| C[Print Already Open]
B -->|No| D{Is Locked?}
D -->|Yes| E{Player Has Key?}
D -->|No| F[Play Opening Sound]
E -->|Yes| G[Unlock and Open]
E -->|No| H[Print Need Key]
F --> I[Open Door]
G --> I
style A fill:#4CAF50,stroke:#2e7d32,color:#fff
style B fill:#ff9800,stroke:#e65100,color:#fff
style D fill:#ff9800,stroke:#e65100,color:#fff
style E fill:#ff9800,stroke:#e65100,color:#fff
style C fill:#9e9e9e,stroke:#616161,color:#fff
style F fill:#2196F3,stroke:#1565c0,color:#fff
style G fill:#2196F3,stroke:#1565c0,color:#fff
style H fill:#9e9e9e,stroke:#616161,color:#fff
style I fill:#4CAF50,stroke:#2e7d32,color:#fff
Figure: Intelligent execution—makes decisions, handles multiple scenarios appropriately.
Now the door checks conditions and responds appropriately. That's the power of flow control!
Categories of Flow Control
| Category | Purpose | Key Nodes |
|---|---|---|
| Conditionals | Make decisions based on conditions | Branch, Switch, Select |
| Loops | Repeat actions multiple times | For Loop, While Loop, ForEach |
| Sequencing | Control execution order and timing | Sequence, Delay, Retriggerable Delay |
| Gates | Open/close execution paths | Gate, MultiGate, Do Once, Do N |
| Boolean Logic | Combine multiple conditions | AND, OR, NOT, XOR |
Execution Flow Basics
Remember: Execution follows white wires. Flow control nodes have multiple white output pins, routing execution down different paths based on conditions.
Figure: Flow control nodes route execution down different paths based on conditions.
Branch: If/Then/Else Logic
The Branch node is your most fundamental flow control tool—it's the Blueprint equivalent of "if/then/else" in traditional programming.
📖 Definition
Branch Node: A decision point that evaluates a boolean condition and routes execution down one of two paths: "True" if the condition is true, "False" if not. Every game decision—"Does the player have enough gold?", "Is the door locked?", "Is health below 20?"—uses a Branch node.
Branch Node Structure
Figure: Branch node with labeled inputs and outputs.
Using Branch Nodes
Basic pattern:
- Right-click in Event Graph → search "Branch"
- Connect execution flow to the Branch input
- Connect a boolean condition to the Condition pin
- Wire the True output to actions that should happen if true
- Wire the False output to actions that should happen if false
Branch Examples
Example 1: Door with Lock Check
Event OnInteract
→ Branch (Condition = bIsLocked)
→ True: Print "Door is locked!"
→ False: Open Door + Play Sound
Example 2: Health Check
TakeDamage(DamageAmount)
→ Subtract DamageAmount from Health
→ Branch (Condition = Health <= 0)
→ True: Player Dies + Game Over
→ False: Update Health Bar
Example 3: Inventory Check
Try to Buy Item
→ Branch (Condition = Gold >= ItemCost)
→ True: Subtract Gold + Add Item to Inventory + Print "Purchased!"
→ False: Print "Not enough gold!"
✅ Pro Tip: Chaining Branches
You can connect the output of one Branch to the input of another to create nested conditions:
Event → Branch (Is Door Locked?)
→ True: Branch (Player Has Key?)
→ True: Unlock + Open
→ False: Show "Need Key" Message
→ False: Open Door Directly
This creates an if-within-if structure—check locked state, then check key possession.
Comparison Operators
Branch nodes need boolean conditions. Often, you create these conditions by comparing values—"Is health greater than 50?", "Is the player's name equal to 'Hero'?", "Is score less than 1000?"
📖 Definition
Comparison Operators: Nodes that compare two values and output a boolean result (true/false). They answer questions like "is A bigger than B?" or "are these two things equal?" The result feeds directly into Branch nodes to make decisions.
The Six Comparison Operators
Figure: All comparison operators with examples and common use cases.
Using Comparison Operators
To create a comparison:
- Right-click in Event Graph
- Search for the operator: "==", ">", "<", etc.
- Or search by type: "Integer > Integer", "Float <= Float"
- Connect the two values you want to compare
- The output is a boolean (true/false)
- Connect output to a Branch node's Condition pin
Practical Example: Health System
flowchart TD
A[TakeDamage Event] --> B[Subtract Damage from Health]
B --> C{Health <= 0?}
C -->|True| D[Player Dies]
C -->|False| E{Health < 20?}
E -->|True| F[Show Warning: Low Health!]
E -->|False| G[Update Health Bar]
D --> H[Game Over Screen]
F --> G
style A fill:#e74c3c,stroke:#c0392b,color:#fff
style B fill:#2196F3,stroke:#1565c0,color:#fff
style C fill:#ff9800,stroke:#e65100,color:#fff
style D fill:#e74c3c,stroke:#c0392b,color:#fff
style E fill:#ff9800,stroke:#e65100,color:#fff
style F fill:#ffc107,stroke:#f57c00,color:#fff
style G fill:#4CAF50,stroke:#2e7d32,color:#fff
style H fill:#9e9e9e,stroke:#616161,color:#fff
Figure: Health system using multiple comparison operators to make layered decisions.
Special Comparison Nodes
| Node | Purpose | Use Case |
|---|---|---|
| Nearly Equal (float) | Compares floats within tolerance | Checking if player reached exact position (floats rarely exactly equal) |
| In Range | Checks if value is between min and max | Is score between 100 and 500? Is angle between 0 and 90? |
| Is Valid | Checks if reference is valid (not null) | Does this Actor reference point to something that exists? |
| Equal (Object) | Checks if two references point to same object | Is this the same Actor I stored earlier? |
Boolean Logic (AND, OR, NOT)
Real-world conditions are often complex: "Open the door if the player has the key AND the door isn't locked" or "Give a powerup if health is low OR time is running out." Boolean logic operators let you combine multiple conditions.
📖 Definition
Boolean Logic: Operations that combine or modify boolean values (true/false). The three fundamental operators—AND, OR, NOT—allow you to build complex conditional statements from simpler ones. They're the building blocks of intelligent decision-making.
The Three Boolean Operators
Figure: Visual truth tables for AND, OR, and NOT operations.
Using Boolean Operators in Blueprints
To create boolean logic:
- Right-click in Event Graph
- Search: "AND", "OR", "NOT"
- Connect boolean inputs (comparison results, variables, etc.)
- Output is a combined boolean
- Connect to Branch condition
Complex Logic Example: Vault Door
flowchart TD
A[Player Interacts with Vault] --> B{Has Red Key?}
B -->|No| C[Show: Need Keys]
B -->|Yes| D{Has Blue Key?}
D -->|No| C
D -->|Yes| E{Is Admin?}
E -->|Yes| F[Open Vault]
E -->|No| G{Door Unlocked?}
G -->|Yes| F
G -->|No| H[Show: Locked]
style A fill:#4CAF50,stroke:#2e7d32,color:#fff
style B fill:#ff9800,stroke:#e65100,color:#fff
style D fill:#ff9800,stroke:#e65100,color:#fff
style E fill:#ff9800,stroke:#e65100,color:#fff
style G fill:#ff9800,stroke:#e65100,color:#fff
style F fill:#4CAF50,stroke:#2e7d32,color:#fff
style C fill:#e74c3c,stroke:#c0392b,color:#fff
style H fill:#e74c3c,stroke:#c0392b,color:#fff
Figure: Complex vault logic using multiple AND/OR conditions.
In Blueprints:
Condition = (HasRedKey AND HasBlueKey AND NOT IsLocked) OR IsAdmin
Branch (Condition)
→ True: Open Vault
→ False: Show Error Message
Order of Operations
When combining operators, Blueprints evaluate left-to-right, but you can control order with parentheses (nesting):
- A AND B OR C — evaluates (A AND B) first, then OR with C
- A AND (B OR C) — evaluates (B OR C) first, then AND with A
In visual Blueprints, nesting is explicit—you wire outputs into inputs to create the structure you want.
✅ Pro Tip: Simplify Complex Logic
If your boolean logic gets too tangled:
- Break it into intermediate variables:
bCanOpenDoor = HasKey AND IsUnlocked - Create helper functions:
CheckDoorRequirements()returns boolean - Use comment boxes to document what each section checks
Readable logic is debuggable logic!
Switch Statements
Branch nodes are great for two-way decisions (true/false). But what if you have multiple options—"What happens based on the player's difficulty level: Easy, Normal, Hard, Expert?" Enter Switch nodes.
📖 Definition
Switch Statement: A multi-way branch that checks a single value against multiple possible options and executes different code for each match. Instead of nested if/else chains, Switch provides a clean, readable way to handle many distinct cases.
Switch vs. Multiple Branches
❌ Multiple Branches (Messy)
Branch (Level == 1)
→ True: Spawn 5 enemies
→ False: Branch (Level == 2)
→ True: Spawn 10 enemies
→ False: Branch (Level == 3)
→ True: Spawn 20 enemies
→ False: ...
Deeply nested, hard to read, error-prone!
✅ Switch (Clean)
Switch on Integer (Level) Case 1: Spawn 5 enemies Case 2: Spawn 10 enemies Case 3: Spawn 20 enemies Default: Spawn 30 enemies
Clean, readable, easy to extend!
Switch Types
Unreal provides Switch nodes for different data types:
| Switch Type | Checks Against | Use Cases |
|---|---|---|
| Switch on Int | Integer values | Levels, difficulty settings, player states (0=idle, 1=walk, 2=run) |
| Switch on String | String values | Character names, team names, item types |
| Switch on Name | Name values | Tags, identifiers (more efficient than String) |
| Switch on Enum | Enumeration values | Weapon types, game states, AI behaviors (best practice) |
| Switch on Byte | Byte values | Small integer ranges (0-255) |
Using Switch Nodes
- Right-click in Event Graph → search "Switch on [Type]"
- Example: "Switch on Int"
- Connect the value to check to the Selection input
- The Switch node shows multiple output execution pins
- To add cases: Right-click node → Add Pin
- Name each pin with the value to match (0, 1, 2, etc.)
- Connect each case to its appropriate logic
- Use the "Default" pin for unmatched cases
Switch Example: Difficulty Settings
flowchart TD
A[Game Start] --> B[Get Difficulty Setting]
B --> C{Switch on Int: Difficulty}
C -->|0: Easy| D[EnemyHealth = 50
PlayerDamage = 150]
C -->|1: Normal| E[EnemyHealth = 100
PlayerDamage = 100]
C -->|2: Hard| F[EnemyHealth = 200
PlayerDamage = 75]
C -->|3: Expert| G[EnemyHealth = 300
PlayerDamage = 50]
C -->|Default| H[Use Normal Settings]
D --> I[Start Level]
E --> I
F --> I
G --> I
H --> I
style A fill:#4CAF50,stroke:#2e7d32,color:#fff
style B fill:#2196F3,stroke:#1565c0,color:#fff
style C fill:#ff9800,stroke:#e65100,color:#fff
style D fill:#4CAF50,stroke:#2e7d32,color:#fff
style E fill:#2196F3,stroke:#1565c0,color:#fff
style F fill:#ff9800,stroke:#e65100,color:#fff
style G fill:#e74c3c,stroke:#c0392b,color:#fff
style H fill:#9e9e9e,stroke:#616161,color:#fff
style I fill:#9c27b0,stroke:#6a1b9a,color:#fff
Figure: Switch statement routing to different difficulty configurations.
Best Practice: Use Enums with Switch
Instead of integers or strings, create an Enumeration (Enum) for cleaner, safer code:
- Content Browser → Right-click → Blueprints → Enumeration
- Name it (e.g.,
E_DifficultyLevel) - Add enumerators: Easy, Normal, Hard, Expert
- Save
- Use Switch on Enum node
- Automatically creates pins for each enum value
Benefits of enums:
- ✅ Type-safe—can't accidentally pass invalid values
- ✅ Self-documenting—"Easy" is clearer than "0"
- ✅ Auto-complete—shows all valid options
- ✅ Refactoring-safe—rename once, updates everywhere
✅ Switch Best Practices
- Always implement the Default case (fallback for unexpected values)
- Prefer enums over integers for readability
- Keep individual cases simple—call functions instead of cramming logic
- Document what each case represents with comments
Loops: For, While, ForEach
Sometimes you need to repeat an action multiple times—"Spawn 10 enemies," "Damage all enemies in range," "Check every item in inventory." Loops execute a block of code repeatedly.
📖 Definition
Loop: A control structure that repeats a section of code multiple times. Loops are essential for working with collections, performing batch operations, and any task that requires repetition. The three main types—For, While, and ForEach—handle different looping scenarios.
The Three Loop Types
flowchart TD
A[Loop Types] --> B[For Loop]
A --> C[While Loop]
A --> D[ForEach Loop]
B --> B1[Fixed number of iterations]
B --> B2[Uses index counter]
B --> B3[Example: Spawn 10 enemies]
C --> C1[Loop until condition false]
C --> C2[Unknown iteration count]
C --> C3[Example: Search until found]
D --> D1[Iterate through array]
D --> D2[Process each element]
D --> D3[Example: Damage all enemies]
style A fill:#667eea,stroke:#4527a0,color:#fff
style B fill:#4CAF50,stroke:#2e7d32,color:#fff
style C fill:#ff9800,stroke:#e65100,color:#fff
style D fill:#2196F3,stroke:#1565c0,color:#fff
style B1 fill:#e8f5e9,stroke:#4CAF50
style B2 fill:#e8f5e9,stroke:#4CAF50
style B3 fill:#e8f5e9,stroke:#4CAF50
style C1 fill:#fff3e0,stroke:#ff9800
style C2 fill:#fff3e0,stroke:#ff9800
style C3 fill:#fff3e0,stroke:#ff9800
style D1 fill:#e3f2fd,stroke:#2196F3
style D2 fill:#e3f2fd,stroke:#2196F3
style D3 fill:#e3f2fd,stroke:#2196F3
Figure: Three loop types with their characteristics and use cases.
1. For Loop
For Loop repeats a fixed number of times, using an index counter.
Structure:
- First Index: Starting number (usually 0)
- Last Index: Ending number (exclusive in some languages, inclusive in UE)
- Loop Body: Execution pin that runs each iteration
- Index: Current iteration number (output)
- Completed: Execution pin after loop finishes
Example: Spawn Multiple Enemies
For Loop (First Index = 0, Last Index = 9)
Loop Body:
→ Spawn Enemy at Random Location
→ Index output shows current number (0, 1, 2, ... 9)
Completed:
→ Print "All enemies spawned!"
This spawns 10 enemies (indices 0 through 9).
2. While Loop
While Loop repeats as long as a condition remains true—useful when you don't know how many iterations you need.
Structure:
- Condition: Boolean input—loop continues while true
- Loop Body: Execution pin that runs each iteration
- Completed: Execution pin after condition becomes false
Example: Search for Item
While Loop (Condition = NOT Found AND Index < ArrayLength)
Loop Body:
→ Check current inventory slot
→ If item matches, set Found = true
→ Increment Index
Completed:
→ If Found: Use item
→ Else: Print "Item not found"
⚠️ While Loop Warning: Infinite Loops
While Loops can run forever if the condition never becomes false:
❌ BAD: While (bIsSearching == true) → Do nothing that changes bIsSearching → Infinite loop! Game freezes!
Always ensure the loop body eventually makes the condition false or use a safety counter.
3. ForEach Loop
ForEach Loop iterates through every element in an array—perfect for processing collections.
Structure:
- Array: The array to iterate through
- Loop Body: Runs once per element
- Array Element: Current element (output)
- Array Index: Current position in array
- Completed: After all elements processed
Example: Damage All Enemies
ForEach Loop (Array = EnemiesInRange)
Loop Body:
→ Get current enemy (Array Element output)
→ Call TakeDamage(50) on enemy
Completed:
→ Print "All enemies damaged"
flowchart TD
A[ForEach Loop Starts] --> B[Get Enemy 1 from Array]
B --> C[Call TakeDamage on Enemy 1]
C --> D[Get Enemy 2 from Array]
D --> E[Call TakeDamage on Enemy 2]
E --> F[Get Enemy 3 from Array]
F --> G[Call TakeDamage on Enemy 3]
G --> H[All Elements Processed]
H --> I[Completed Pin Fires]
style A fill:#4CAF50,stroke:#2e7d32,color:#fff
style B fill:#2196F3,stroke:#1565c0,color:#fff
style C fill:#ff9800,stroke:#e65100,color:#fff
style D fill:#2196F3,stroke:#1565c0,color:#fff
style E fill:#ff9800,stroke:#e65100,color:#fff
style F fill:#2196F3,stroke:#1565c0,color:#fff
style G fill:#ff9800,stroke:#e65100,color:#fff
style H fill:#9c27b0,stroke:#6a1b9a,color:#fff
style I fill:#4CAF50,stroke:#2e7d32,color:#fff
Figure: ForEach Loop processes every element in an array sequentially.
Loop Control Nodes
| Node | Purpose |
|---|---|
| Break | Exit the loop immediately (skip remaining iterations) |
| Continue | Skip current iteration, move to next |
Example with Break:
ForEach Loop (Array = Enemies)
Loop Body:
→ If enemy health <= 0: Continue (skip dead enemies)
→ If enemy is boss: Apply damage, then Break (stop after boss)
→ Else: Apply damage
Loop Performance Notes
- ⚠️ Avoid loops in Event Tick when possible (runs 60+ times/second)
- ✅ Use loops in BeginPlay, function calls, or timer events
- ⚠️ Large loops (1000+ iterations) can cause frame hitches
- ✅ For massive operations, spread across multiple frames using timers
Sequence and Delay Nodes
Sometimes you need to control the order and timing of execution. Sequence manages order, Delay manages timing.
Sequence Node
The Sequence node has multiple output pins that fire in order—perfect for executing actions step-by-step.
Structure:
- One input execution pin
- Multiple output pins (Then 0, Then 1, Then 2, etc.)
- Each output fires in sequence
- Right-click → Add pin to add more outputs
Example: Opening a Treasure Chest
OnInteract → Sequence
Then 0: Play Opening Animation
Then 1: Spawn Particles (sparkles)
Then 2: Play Sound (chest open)
Then 3: Add Gold to Player
Then 4: Destroy Chest
All five actions execute immediately, but in guaranteed order.
flowchart LR
A[Event] --> B[Sequence]
B -->|Then 0| C[Action 1]
B -->|Then 1| D[Action 2]
B -->|Then 2| E[Action 3]
B -->|Then 3| F[Action 4]
style A fill:#4CAF50,stroke:#2e7d32,color:#fff
style B fill:#ff9800,stroke:#e65100,color:#fff
style C fill:#2196F3,stroke:#1565c0,color:#fff
style D fill:#2196F3,stroke:#1565c0,color:#fff
style E fill:#2196F3,stroke:#1565c0,color:#fff
style F fill:#2196F3,stroke:#1565c0,color:#fff
Figure: Sequence node ensures actions execute in order.
Delay Node
The Delay node pauses execution for a specified duration—essential for timing events.
Structure:
- Duration: How many seconds to wait
- Completed: Fires after delay finishes
Example: Delayed Explosion
Throw Grenade
→ Spawn Grenade Actor
→ Delay (3.0 seconds)
→ Spawn Explosion at Grenade Location
→ Destroy Grenade
Retriggerable Delay
Retriggerable Delay resets if triggered again before completing—useful for "wait until player stops doing something" scenarios.
Example: Auto-Save After Inactivity
On Any Player Action (movement, shooting, etc.)
→ Retriggerable Delay (30 seconds)
→ If player inactive for 30 seconds: Auto-Save Game
If player moves at 29 seconds, delay resets to 30 seconds.
Combining Sequence and Delay
Use them together for timed sequences:
Boss Death → Sequence
Then 0: Play Death Animation → Delay (2s) → Spawn Loot
Then 1: Shake Camera
Then 2: Show Victory Message → Delay (3s) → Load Next Level
sequenceDiagram
participant E as Event
participant S as Sequence
participant A1 as Action 1
participant D1 as Delay (2s)
participant A2 as Action 2
participant A3 as Action 3
participant D2 as Delay (3s)
participant A4 as Action 4
E->>S: Trigger
S->>A1: Then 0
A1->>D1: Wait
Note over D1: 2 seconds pass
D1->>A2: Continue
S->>A3: Then 1 (immediate)
A3->>D2: Wait
Note over D2: 3 seconds pass
D2->>A4: Continue
Figure: Sequence with Delays creates timed multi-step events.
Gates and FlipFlops
Gates control whether execution can flow through—like a door that can be opened or closed. FlipFlops alternate between two states each time they're triggered.
Gate Node
Gate blocks execution until opened.
Pins:
- Enter: Tries to pass through gate
- Open: Opens the gate
- Close: Closes the gate
- Toggle: Flips gate state
- Exit: Execution continues (if gate is open)
- Start Closed: Boolean setting (default state)
Example: Wave System
Gate (Start Closed = true)
Enter: Player tries to exit spawn room
Exit: Actually exit
On Wave Clear:
→ Open Gate (players can now leave)
On Boss Spawn:
→ Close Gate (trap players in arena)
MultiGate
MultiGate cycles through multiple outputs in sequence or randomly.
Use case: NPC dialogue that changes each interaction:
Talk to NPC → MultiGate
Out 1: "Hello, stranger!"
Out 2: "Back again?"
Out 3: "You're persistent!"
Out 4: "What do you want now?"
(Then loops or stops, depending on settings)
Do Once
Do Once allows execution once, then blocks—perfect for one-time events.
Example: Tutorial Message
Player Enters Area → Do Once
→ Show Tutorial: "Press E to interact"
(Won't show again, even if player re-enters area)
Reset pin: Call to allow firing again
Do N
Do N allows execution N times, then blocks.
Example: Limited Use Item
Use Healing Potion → Do N (N = 3)
→ Heal Player
→ On Counter: Display "Uses remaining: X"
After 3 uses, won't fire anymore.
FlipFlop
FlipFlop alternates between two outputs each time triggered—like a light switch.
Example: Toggle Light
Press Light Switch → FlipFlop
A: Turn Light On
B: Turn Light Off
First press: A fires (light on)
Second press: B fires (light off)
Third press: A fires (light on)
...and so on
stateDiagram-v2
[*] --> StateA
StateA --> StateB: Trigger
StateB --> StateA: Trigger
note right of StateA
Output A fires
(e.g., Light On)
end note
note right of StateB
Output B fires
(e.g., Light Off)
end note
Figure: FlipFlop alternates between two states on each trigger.
Advanced Flow Control Patterns
State Machines
A state machine manages complex behaviors with distinct states and transitions.
Example: Enemy AI States
stateDiagram-v2
[*] --> Patrol
Patrol --> Chase: Player Spotted
Chase --> Attack: In Attack Range
Chase --> Patrol: Player Lost
Attack --> Chase: Player Out of Range
Attack --> Dead: Health <= 0
Chase --> Dead: Health <= 0
Patrol --> Dead: Health <= 0
Dead --> [*]
note right of Patrol
Walk waypoint route
Check for player
end note
note right of Chase
Move toward player
Check distance
end note
note right of Attack
Play attack animation
Deal damage
end note
Figure: Enemy AI state machine with transitions based on conditions.
Implementation in Blueprints:
- Create enum:
E_EnemyState(Patrol, Chase, Attack, Dead) - Variable:
CurrentState(type: E_EnemyState) - Event Tick → Switch on Enum (CurrentState)
- Patrol case: Execute patrol logic, check for player
- Chase case: Move toward player, check distance
- Attack case: Attack animation, deal damage
- Dead case: Do nothing
- Each state checks conditions and sets CurrentState to transition
Cooldown Systems
Prevent actions from happening too frequently:
Ability Use → Branch (Can Use Ability?)
Condition = CurrentTime >= LastUseTime + CooldownDuration
True:
→ Execute Ability
→ Set LastUseTime = Current Time
False:
→ Print "Ability on cooldown"
Chaining Actions with Delays
Create cinematic sequences:
Trigger Cutscene → Sequence
Then 0: Fade to Black → Delay (1s) → Move Camera to Position
Then 1: Delay (2s) → Character Speaks → Delay (3s) → End Speech
Then 2: Delay (6s) → Fade from Black → Return Control to Player
🏋️ Hands-On Exercise: Smart Door with Complex Logic
Build a door with multiple unlock conditions and cooldown mechanics.
Requirements
- Door requires either Red Key OR Blue Key to unlock
- Once unlocked, door opens for 5 seconds then closes automatically
- Door has 10-second cooldown after closing before it can open again
- Display appropriate messages for each scenario
Part 1: Setup Variables
Create BP_SmartDoor with variables:
bIsOpen(Boolean) = falsebIsLocked(Boolean) = truebHasRedKey(Boolean) = false (Instance Editable)bHasBlueKey(Boolean) = false (Instance Editable)LastOpenTime(Float) = 0.0CooldownDuration(Float) = 10.0
Part 2: Check Access Function
Create function: CanAccessDoor() returns Boolean
Get Current Time
Branch (Current Time >= LastOpenTime + CooldownDuration)
True:
→ Branch (bHasRedKey OR bHasBlueKey)
True: Return true
False: Return false
False:
→ Return false
Part 3: OnInteract Event
OnInteract → Branch (CanAccessDoor?)
True:
→ Sequence
Then 0: Open Door + Print "Door Opening!"
Then 1: Delay (5s) → Close Door + Print "Door Closing"
Then 2: Set LastOpenTime = Current Time
False:
→ Switch on Int (Determine why failed)
Case: Too Soon → Print "Door on cooldown"
Case: No Key → Print "Need Red or Blue Key"
Part 4: Test
- Place door in level
- Test scenarios:
- No keys: Should show "Need key" message
- With Red Key: Opens, closes after 5s
- Try opening immediately after close: "On cooldown"
- Wait 10s, try again: Opens successfully
✅ Checkpoint: What did you learn?
This exercise combined:
- Boolean Logic: OR operator for key check
- Comparison: Time checks for cooldown
- Branches: Nested conditionals
- Sequence: Ordered door operations
- Delay: Timed door closing
- Switch: Different failure messages
Challenge: Wave Spawner
Create a wave spawner that:
- Uses For Loop to spawn N enemies per wave
- Uses Delay between each spawn (0.5s)
- After wave completes, uses Retriggerable Delay (10s) before next wave
- Uses Switch to set different enemy counts per wave (Wave 1: 5, Wave 2: 8, Wave 3: 12)
- Uses Do Once to show "Wave Started" message
Summary
Flow control transforms simple Blueprint scripts into intelligent, dynamic gameplay systems. Master these concepts and you can build any game logic imaginable.
Key Takeaways
- 🔀 Flow Control determines which nodes execute based on conditions, loops, or explicit control—essential for game intelligence
- 🔁 Branch Nodes create if/then/else logic with true/false execution paths
- 📊 Comparison Operators (==, !=, >, <, >=, <=) evaluate conditions and return boolean results
- 🧮 Boolean Logic (AND, OR, NOT) combines multiple conditions into complex decision-making
- 🔄 Switch Statements handle multi-way branching cleanly—use enums for best results
- 🔁 Loops repeat actions: For (fixed count), While (until condition), ForEach (array iteration)
- ⏱️ Sequence and Delay control execution order and timing for coordinated events
- 🚪 Gates and FlipFlops control execution flow: Gates block/allow, FlipFlops alternate states
- 🤖 State Machines manage complex behaviors with distinct states and transitions
- ✅ Best Practices: Use enums with Switch, validate While Loop conditions, avoid loops in Tick, break complex logic into functions
What's Next?
With flow control mastered, the next lesson explores Lesson 3.4: Blueprint Functions and Macros. You'll learn to organize code into reusable functions, create custom events, use macros for complex node groups, and build maintainable Blueprint architectures.
✅ Self-Check Quiz
Before moving on, make sure you can answer these questions:
- What's the difference between Branch and Switch?
- Name the six comparison operators and their symbols.
- What's the difference between AND and OR logic?
- When should you use a For Loop vs. a ForEach Loop?
- What's the danger of While Loops?
- What does a Sequence node do?
- What's the difference between Delay and Retriggerable Delay?
- What's a FlipFlop node used for?
📝 Show Answers
- Branch handles two-way decisions (true/false). Switch handles multi-way decisions (many possible values).
- == (equal), != (not equal), > (greater), < (less), >= (greater or equal), <= (less or equal).
- AND requires both conditions true. OR requires at least one condition true.
- For Loop when you know the exact number of iterations. ForEach Loop when iterating through an array of unknown size.
- While Loops can run forever if the condition never becomes false, freezing the game.
- Sequence node executes multiple outputs in guaranteed order (Then 0, Then 1, Then 2, etc.).
- Delay waits a fixed time. Retriggerable Delay resets if triggered again before completing.
- FlipFlop alternates between two outputs each time triggered—useful for toggle behaviors like light switches.