Skip to main content
Version: Next

Factory NPC Queueing: Pools, Token Gates and What StateTree Is For

"A crowd of NPCs queuing through one entrance" looks like a pathfinding problem; in practice three things are stacked together: entity lifetime (who exists), resource slots (who may enter), and individual behaviour (what happens after entering). Write all three inside one actor's Tick and the system collapses as soon as the numbers grow.

Class names and subsystem interfaces follow the stable UE5 shape; exact signatures shift between versions. Check AIController.h, StateTreeComponent.h and SmartObjectSubsystem.h in the version you build.

Three layers of responsibility​

LayerOwnsMust not ownTypical carrier
Entitywhether an NPC exists, is visible, collidesbusiness rulesobject pool + APawn/ACharacter
Slotswho may enter, in what order, timeout releasebehavioura queue manager (world subsystem)
Behaviourwhat to do inside, how to failslot allocationStateTree / behaviour tree
Interactionwhere to stand, which posequeue orderSmartObject

The test for a clean split is simple: changing "capacity from 1 to 3" should touch exactly one layer. If it needs a state tree edit, an actor edit and a UI change, the boundaries are wrong.

Entity layer: the release contract of a pool​

NPCs in a factory scene repeatedly enter and leave view; SpawnActor / Destroy (construction, component registration, GC pressure) costs far more than reuse. Pooling itself is easy — releasing cleanly is the hard part:

void UVMPawnPool::Release(APawn* Pawn)
{
if (!IsValid(Pawn)) return;

// 1. behaviour layer first: stop the tree so async tasks do not keep running
if (UStateTreeComponent* ST = Pawn->FindComponentByClass<UStateTreeComponent>())
{
ST->StopLogic(TEXT("PoolRelease"));
}

// 2. timers must be cleared: stale lambdas capture the pooled pawn
Pawn->GetWorldTimerManager().ClearAllTimersForObject(Pawn);

// 3. unbind delegates: the least obvious leak in pooled objects
Pawn->OnDestroyed.RemoveAll(this);

// 4. reset physical and visual state
Pawn->SetActorEnableCollision(false);
Pawn->SetActorHiddenInGame(true);
Pawn->SetActorTickEnabled(false);
Pawn->SetActorLocation(FVector(0.f, 0.f, -100000.f));

FreeList.Add(Pawn);
}

Write the contract as a checklist and mirror Acquire exactly:

What Acquire doesWhat Release must undo
SetActorHiddenInGame(false)back to true
binds OnDestroyed / damage delegatesRemoveAll
starts the StateTreeStopLogic and wait for async tasks
SetTimer for patrol intervalsClearAllTimersForObject
registers with the AI perception systemunregister

Each omission has a different symptom (invisible NPCs, ghost timers, dead references piling up in perception), but all of them show up as "slower the longer it runs" rather than an immediate crash.

Slot layer: token gating​

Capacity must be owned by a single authority. A UWorldSubsystem is the safest carrier: it lives and dies with the level and can arbitrate on the server without any replication.

USTRUCT()
struct FQueueTicket
{
GENERATED_BODY()

UPROPERTY() TWeakObjectPtr<APawn> Pawn;
UPROPERTY() double RequestTime = 0.0;
UPROPERTY() int32 Priority = 0; // lower wins; ordinary NPC = 100
};

class UVMTrafficGate : public UWorldSubsystem
{
public:
bool TryAcquire(APawn* Pawn, int32 Priority, double Now);
void Release(APawn* Pawn);
void Tick(float DeltaTime); // driven by the subsystem TickFunction, not one actor

private:
TArray<FQueueTicket> Waiting; // sorted by Priority then RequestTime
TSet<TWeakObjectPtr<APawn>> Holding;
int32 Capacity = 3;
};

Three problems that must be handled explicitly:

ProblemConsequence if ignoredHandling
Fairnessdistant NPCs never win, near ones cut in repeatedlysort by (Priority, RequestTime), never by distance
Starvationhigh-priority requests keep arriving, ordinary ones wait foreverraise priority after a wait threshold (aging)
Deadlockthe token holder is destroyed, teleported or stuckforced release on hold timeout + Release in EndPlay

Deadlock is the first thing to break in production. The cheapest safety net is unconditional release in EndPlay, plus a hold timeout:

void UVMTrafficGate::Tick(float DeltaTime)
{
const double Now = GetWorld()->GetTimeSeconds();

for (auto It = Holding.CreateIterator(); It; ++It)
{
APawn* Pawn = It->Get();
if (!IsValid(Pawn) || Now - HoldStart.FindRef(*It) > MaxHoldSeconds)
{
ReleaseInternal(*It); // must not call the public Release that relocks
It.RemoveCurrent();
}
}
}

Behaviour layer: why state belongs in StateTree​

The same "waiting" state written inside Tick becomes a pile of if (bWaiting && !bArrived && ...). In a behaviour tree, node order expresses logic but every branch change needs an asset edit. StateTree earns its place for two reasons: states and transitions are data, and tasks can be gated by conditions.

RequirementTick-styleStateTree
Add a "pay the fee" stepone more bool and one more branchone more State with enter/exit conditions
Abandon the queue midwaycheck bCancelled everywhereone global transition to Abort
Debug what it is doingbreakpoints on variablesthe running state is highlighted
Designers reorder stepscode changeasset change

A workable set of states:

The key is that "waiting for a slot" must be its own State, not a loop inside Approach. That way timeouts, priority raises and abandonment are all expressible as transitions, with no flags buried in movement code.

The seam with SmartObject​

SmartObject answers "where and in what pose", not "who goes first". Wire it as follows:

  1. only request a SmartObject after the slot layer granted a token
  2. use FSmartObjectRequestFilter to restrict tags (e.g. Slot.Queue) so you do not steal someone else's workstation
  3. on a successful Claim, hold the FSmartObjectClaimHandle; release it on leave
  4. on a failed claim, release the token back to the slot layer

Item 4 is the classic omission: the claim fails, the code just returns, the token is never released, and a few minutes later the whole gate is stuck.

Failure modes at a glance​

SymptomMost likely causeWhat to inspect
NPCs overlap at the doorgate capacity disagrees with physical widthCapacity versus door width and capsule radius
Everyone stands still after a whileperception not refreshed, Wait has no transitioncurrent state in the StateTree runtime
Slower the longer it runspooled objects keep delegates or timerswhether Release runs to completion
Occasional hard stallsclaim failure never releases the tokenwhether Holding equals Capacity while idle
Clients see NPCs teleportarbitration on the server, replication too slowreplication rate and prediction

In one line​

Entities use pools, slots use gates, behaviour uses trees. With clear boundaries, "capacity 1 → 3" is a single number; with blurred ones, every requirement change touches five files.