TExcelTAD
Home › Unreal Engine 5 with C++ › EQS & StateTree

EQS & StateTree

Two more AI tools round out Unreal's set. The Environment Query System (EQS) answers spatial questions: where should I go? StateTree is a newer, general-purpose way to structure decisions, an alternative to Behavior Trees that combines a state machine with a tree's hierarchy.

EQS: generate, test, score

An Env Query asset has a generator that produces candidate items (points or actors), and a list of tests that filter and score them. The best item wins.

Generator Produces
Points: Grid / Circle / Donut / Cone points around the querier or a context
Points: Pathing Grid points reachable on the NavMesh
Actors Of Class actors (pickups, cover objects, allies)
Test Typical use
Distance (to a context) prefer close points, or keep a preferred range
Trace (to a context) filter for points the player can't see: cover
Dot prefer points in front of / behind someone
Pathfinding (path exists / path length) discard unreachable points
Overlap discard points inside geometry

Each test can filter (drop items that fail), score (add a normalized 0–1 score times a weight), or both. Contexts name the things tests measure against: EnvQueryContext_Querier (the AI itself), EnvQueryContext_Item, or your own C++ / Blueprint context class returning the target.

From a Behavior Tree, use the Run EQS Query task, which writes the result into a blackboard key. From C++:

cpp
#include "EnvironmentQuery/EnvQueryManager.h"

void AArenaAIController::FindCover()
{
    FEnvQueryRequest Request(CoverQuery, GetPawn());                 // UPROPERTY TObjectPtr<UEnvQuery> CoverQuery
    Request.Execute(EEnvQueryRunMode::SingleResult, this, &AArenaAIController::OnCoverQueryFinished);
}

void AArenaAIController::OnCoverQueryFinished(TSharedPtr<FEnvQueryResult> Result)
{
    if (Result.IsValid() && Result->IsSuccessful())
    {
        MoveToLocation(Result->GetItemAsLocation(0));
    }
}

EQS queries are time-sliced across frames, so results arrive later. That is fine for AI and is why the callback exists. Use the EQS Testing Pawn (place it in the level, assign a query) to see scores drawn in the editor, and the EQS category of the Gameplay Debugger at runtime.

A runnable EQS model: finding cover

The model generates a 5×5 grid of points (200 cm apart, centred on the arena origin), filters out points the player can see (a wall blocks some sight lines), scores the rest by distance to the AI (closer is better, weight 1) and by distance from the player (farther is better, weight 0.5), and prints the ranking.

cpp · try it yourself
#include <algorithm>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <vector>

struct V2 { double x, y; };
double Dist(V2 a, V2 b) { return std::hypot(a.x - b.x, a.y - b.y); }

// Does segment p-q cross the wall segment from a to b?
bool Crosses(V2 p, V2 q, V2 a, V2 b) {
    auto cross = [](V2 o, V2 u, V2 v) { return (u.x - o.x) * (v.y - o.y) - (u.y - o.y) * (v.x - o.x); };
    double d1 = cross(a, b, p), d2 = cross(a, b, q), d3 = cross(p, q, a), d4 = cross(p, q, b);
    return d1 * d2 < 0 && d3 * d4 < 0;
}

struct Item { V2 P; double Score = 0; };

void Normalize(std::vector<Item>& items, const std::vector<double>& raw, double weight, bool higherIsBetter) {
    double lo = *std::min_element(raw.begin(), raw.end()), hi = *std::max_element(raw.begin(), raw.end());
    for (size_t i = 0; i < items.size(); i++) {
        double n = hi > lo ? (raw[i] - lo) / (hi - lo) : 1;
        items[i].Score += weight * (higherIsBetter ? n : 1 - n);
    }
}

int main() {
    std::cout << std::fixed << std::setprecision(2);
    const V2 ai{200, -400}, player{800, 0};             // the AI stands in the open
    const V2 wallA{300, -150}, wallB{300, 250};               // a low wall between them

    std::vector<Item> items;                                  // generator: grid, 200 cm spacing
    for (int gy = -2; gy <= 2; gy++)
        for (int gx = -2; gx <= 2; gx++) items.push_back({{gx * 200.0, gy * 200.0}});
    std::cout << "generated " << items.size() << " points\n";

    std::erase_if(items, [&](const Item& it) { return !Crosses(it.P, player, wallA, wallB); });
    // ^ Trace test as a filter: keep points whose line to the player is blocked by the wall.
    std::cout << "after trace filter: " << items.size() << " hidden points\n";

    std::vector<double> toAi, toPlayer;
    for (auto& it : items) { toAi.push_back(Dist(it.P, ai)); toPlayer.push_back(Dist(it.P, player)); }
    Normalize(items, toAi, 1.0, /*higherIsBetter*/ false);     // Distance to querier: closer is better
    Normalize(items, toPlayer, 0.5, /*higherIsBetter*/ true);  // Distance to player: farther is better

    std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
        return a.Score != b.Score ? a.Score > b.Score : (a.P.y != b.P.y ? a.P.y < b.P.y : a.P.x < b.P.x);
    });
    for (size_t i = 0; i < 5; i++)                            // the five best
        std::cout << "  #" << i + 1 << " (" << std::setw(7) << items[i].P.x << ", " << std::setw(7) << items[i].P.y
                  << ") score " << items[i].Score << "\n";
}
generated 25 points
after trace filter: 13 hidden points
  #1 (   0.00, -200.00) score 1.17
  #2 (-200.00, -200.00) score 1.09
  #3 (-400.00, -200.00) score 0.98
  #4 (   0.00,    0.00) score 0.92
  #5 (-200.00,    0.00) score 0.91

The winner is a point that is both close to the AI and shielded by the wall. Weights are the designer's knobs: raise the "far from player" weight and the AI prefers retreating to cover farther back.

StateTree

StateTree (plugins StateTree and GameplayStateTree) is a hierarchical state machine whose states hold tasks, with transitions between states driven by conditions and events. Evaluators and global tasks compute values that conditions and tasks bind to, through property bindings instead of a blackboard. For AI, add a UStateTreeAIComponent to the AIController (or a UStateTreeComponent to any actor) and assign a StateTree asset that uses the matching schema.

text
Root
├─ Idle          tasks: [Play idle anim]            transitions: on Event "Alert" -> Combat
├─ Patrol        tasks: [Move to next waypoint]     transitions: on Succeeded -> Patrol, on Event "Alert" -> Combat
└─ Combat        (selects a child each time it enters)
   ├─ Chase      enter if Distance(Target) > 200     tasks: [Move to target]
   └─ Attack     enter if Distance(Target) <= 200    tasks: [Play attack montage]   transitions: on Completed -> Combat

A C++ task is a USTRUCT. Its per-instance data lives in a separate struct:

cpp
// ArenaStateTreeTasks.h (StateTree's C++ API has evolved across 5.x; check the headers of your version)
#pragma once

#include "StateTreeTaskBase.h"
#include "StateTreeExecutionContext.h"
#include "ArenaStateTreeTasks.generated.h"

USTRUCT()
struct FArenaWaitTaskInstanceData
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, Category = "Parameter")
    float Duration = 1.f;

    float Elapsed = 0.f;
};

USTRUCT(meta = (DisplayName = "Arena Wait"))
struct FArenaWaitTask : public FStateTreeTaskCommonBase
{
    GENERATED_BODY()

    using FInstanceDataType = FArenaWaitTaskInstanceData;
    virtual const UStruct* GetInstanceDataType() const override { return FInstanceDataType::StaticStruct(); }

    virtual EStateTreeRunStatus EnterState(FStateTreeExecutionContext& Context, const FStateTreeTransitionResult& Transition) const override
    {
        Context.GetInstanceData(*this).Elapsed = 0.f;
        return EStateTreeRunStatus::Running;
    }

    virtual EStateTreeRunStatus Tick(FStateTreeExecutionContext& Context, const float DeltaTime) const override
    {
        FInstanceDataType& Data = Context.GetInstanceData(*this);
        Data.Elapsed += DeltaTime;
        return Data.Elapsed >= Data.Duration ? EStateTreeRunStatus::Succeeded : EStateTreeRunStatus::Running;
    }
};

The task struct is const and shared; anything that changes per AI goes in the instance data. That is the same rule as Behavior Tree node memory, enforced by the type system.

Behavior Tree or StateTree?

Behavior Tree StateTree
Model priority tree + blackboard, event-driven aborts hierarchical state machine + property bindings
Strengths mature, many examples, great debugger, EQS integration explicit states, cheaper, works for non-AI logic (doors, Smart Objects, Mass crowds)
Weak spots blackboard keys as strings; "what state is it in?" is less obvious newer; API changed between 5.x releases

Both are valid in UE 5.x. Epic's newer samples and systems (Smart Objects, Mass, the Game Animation Sample) lean on StateTree. Many shipped games use Behavior Trees. Pick one per project and stick to it.

Test yourself

In EQS, what is a Trace test typically used for when looking for cover?

  1. Scoring by distance
  2. Filtering out points the player can see
  3. Generating points
  4. Moving the AI

Where does a StateTree task keep values that differ per AI?

  1. In the task struct's members
  2. In its instance data struct
  3. In global variables
  4. In the blackboard only

Why does the C++ EQS request take a callback?

  1. EQS only runs in Blueprints
  2. Queries are time-sliced and finish on a later frame
  3. To replicate the result
  4. Callbacks are faster