Skip to content

77 game-dev skills for AI coding agents — Godot, Unity, Unreal, Phaser, PixiJS, three.js, Bevy, pygame, LÖVE, Roblox. Portable SKILL.md Agent Skills (the format Anthropic launched as Claude Skills), with a router that loads the right skill for your engine and task. Runs in Claude Code, Cursor, Kiro, Codex, Copilot, Gemini CLI and more.

fix(unreal): make latent BTTask example abort-safe with per-AI node memory

Kiro Crew676ab59f41ba
diff --git a/skills/unreal/unreal-behavior-trees/SKILL.md b/skills/unreal/unreal-behavior-trees/SKILL.md
index 5d5d230..f552227 100644
--- a/skills/unreal/unreal-behavior-trees/SKILL.md
+++ b/skills/unreal/unreal-behavior-trees/SKILL.md
@@ -102,6 +102,9 @@ void AEnemyAIController::SetTarget(AActor* Target)
None; set it to Self/Lower Priority/Both so the tree re-evaluates when the key changes.
- **A task hangs the tree** — a custom task returned `InProgress` and never calls
`FinishLatentTask`. Always complete latent tasks.
+- **AI behaves strangely only when several NPCs share a tree** — a custom task stores run state
+ in member variables. Task nodes are shared by every AI using the asset unless instanced; keep
+ per-AI state in node memory (see the reference).
- **Blackboard key typos** — `SetValueAsObject("Taget", ...)` silently does nothing; match the
key name and type exactly, or use a cached `FBlackboardKeySelector`.
- **Sequence vs Selector confusion** — Sequence = AND (stops on first failure); Selector = OR
@@ -110,7 +113,8 @@ void AEnemyAIController::SetTarget(AActor* Target)
## References
- For a **custom C++ `UBTTaskNode`** (instant and latent `ExecuteTask` returning `EBTNodeResult`,
- with a `FBlackboardKeySelector`), read `references/custom-bttask.md`.
+ per-AI node memory, `AbortTask`, and a `FBlackboardKeySelector`), read
+ `references/custom-bttask.md`.
- Primary docs: "Behavior Trees in Unreal Engine"
(`https://dev.epicgames.com/documentation/en-us/unreal-engine/behavior-trees-in-unreal-engine`).
diff --git a/skills/unreal/unreal-behavior-trees/references/custom-bttask.md b/skills/unreal/unreal-behavior-trees/references/custom-bttask.md
index 5cc5080..1a61934 100644
--- a/skills/unreal/unreal-behavior-trees/references/custom-bttask.md
+++ b/skills/unreal/unreal-behavior-trees/references/custom-bttask.md
@@ -55,31 +55,93 @@ EBTNodeResult::Type UBTTask_ClearTarget::ExecuteTask(UBehaviorTreeComponent& Own
## Latent task (finishes over time)
Return `InProgress`, then call `FinishLatentTask` when the work completes (e.g. a timer, an
-async query, or a delegate callback).
+async query, or a delegate callback). Tasks are **not instanced** by default: one node object is
+shared by every AI running the tree, so per-run state (here the timer handle) goes in the
+node's instance memory, never in member variables.
```cpp
+// BTTask_WaitRandom.h
+#pragma once
+#include "CoreMinimal.h"
+#include "BehaviorTree/BTTaskNode.h"
+#include "BTTask_WaitRandom.generated.h"
+
+struct FBTWaitRandomMemory
+{
+ FTimerHandle TimerHandle;
+};
+
+UCLASS()
+class MYGAME_API UBTTask_WaitRandom : public UBTTaskNode
+{
+ GENERATED_BODY()
+public:
+ virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp,
+ uint8* NodeMemory) override;
+ virtual EBTNodeResult::Type AbortTask(UBehaviorTreeComponent& OwnerComp,
+ uint8* NodeMemory) override;
+
+ virtual uint16 GetInstanceMemorySize() const override { return sizeof(FBTWaitRandomMemory); }
+ virtual void InitializeMemory(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
+ EBTMemoryInit::Type InitType) const override
+ {
+ InitializeNodeMemory<FBTWaitRandomMemory>(NodeMemory, InitType);
+ }
+ virtual void CleanupMemory(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
+ EBTMemoryClear::Type CleanupType) const override
+ {
+ CleanupNodeMemory<FBTWaitRandomMemory>(NodeMemory, CleanupType);
+ }
+
+ UPROPERTY(EditAnywhere, Category = "Wait") float MinTime = 1.f;
+ UPROPERTY(EditAnywhere, Category = "Wait") float MaxTime = 3.f;
+};
+```
+
+```cpp
+// BTTask_WaitRandom.cpp
+#include "BTTask_WaitRandom.h"
+#include "BehaviorTree/BehaviorTreeComponent.h"
+#include "TimerManager.h"
+
EBTNodeResult::Type UBTTask_WaitRandom::ExecuteTask(UBehaviorTreeComponent& OwnerComp,
uint8* NodeMemory)
{
- AAIController* AICon = OwnerComp.GetAIOwner();
- if (!AICon) return EBTNodeResult::Failed;
+ UWorld* World = OwnerComp.GetWorld();
+ if (!World) return EBTNodeResult::Failed;
+ FBTWaitRandomMemory* Memory = CastInstanceNodeMemory<FBTWaitRandomMemory>(NodeMemory);
const float Delay = FMath::FRandRange(MinTime, MaxTime);
- // Schedule completion; capture the component so we can finish the right task instance.
- FTimerHandle Handle;
- AICon->GetWorldTimerManager().SetTimer(Handle, FTimerDelegate::CreateLambda(
- [&OwnerComp, this]()
+ // Weak pointer: the component can be destroyed before the timer fires.
+ TWeakObjectPtr<UBehaviorTreeComponent> WeakComp(&OwnerComp);
+ World->GetTimerManager().SetTimer(Memory->TimerHandle,
+ FTimerDelegate::CreateWeakLambda(this, [this, WeakComp]()
{
- FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded); // resumes the tree
- }), Delay, /*loop*/ false);
+ if (UBehaviorTreeComponent* Comp = WeakComp.Get())
+ {
+ FinishLatentTask(*Comp, EBTNodeResult::Succeeded); // resumes the tree
+ }
+ }), Delay, /*bLoop*/ false);
return EBTNodeResult::InProgress; // tree waits on this node until FinishLatentTask
}
+
+EBTNodeResult::Type UBTTask_WaitRandom::AbortTask(UBehaviorTreeComponent& OwnerComp,
+ uint8* NodeMemory)
+{
+ // A higher-priority branch took over: cancel the pending timer so it can't finish later.
+ if (UWorld* World = OwnerComp.GetWorld())
+ {
+ World->GetTimerManager().ClearTimer(
+ CastInstanceNodeMemory<FBTWaitRandomMemory>(NodeMemory)->TimerHandle);
+ }
+ return EBTNodeResult::Aborted;
+}
```
-If a latent task can be aborted by the tree (e.g. a higher-priority branch takes over),
-override `AbortTask` to cancel timers/queries and return `EBTNodeResult::Aborted`.
+`AbortTask` returns `Aborted` when it can stop immediately; return `InProgress` instead and call
+`FinishLatentAbort(OwnerComp)` later if cancelling is itself asynchronous.
## Reading and writing typed Blackboard values
@@ -95,8 +157,14 @@ BB->SetValueAsBool(TEXT("bIsInvestigating"), true);
- Set `NodeName` in the constructor so the node reads clearly in the BT graph.
- `OwnerComp.GetAIOwner()` gives the `AAIController`; `GetAIOwner()->GetPawn()` the controlled
pawn — use these instead of caching world pointers.
-- For nodes that need per-instance memory (counters, handles), override `GetInstanceMemorySize`
- and use the `NodeMemory` block; for simple cases, member UPROPERTYs on a non-instanced node
- are shared across all uses, so prefer instance memory or instanced nodes when state matters.
+- For nodes that need per-instance memory (counters, handles), override
+ `GetInstanceMemorySize`, construct and destroy the block with `InitializeNodeMemory<T>` /
+ `CleanupNodeMemory<T>`, and read it with `CastInstanceNodeMemory<T>` (as in the latent task
+ above). Member UPROPERTYs on a non-instanced node are shared across all uses; treat them as
+ read-only settings.
+- A bare `FBlackboardKeySelector` offers every key in the editor and only `SelectedKeyName` is
+ usable until resolved. Deriving from `UBTTask_BlackboardBase` gives you a `BlackboardKey`
+ that is resolved in `InitializeFromAsset`; with your own selector, add a type filter in the
+ constructor (e.g. `AddObjectFilter`) and call `ResolveSelectedKey` in `InitializeFromAsset`.
- A custom **Service** subclasses `UBTService` and overrides `TickNode`; a custom **Decorator**
subclasses `UBTDecorator` and overrides `CalculateRawConditionValue`.