К основному содержанию
скилл CX Codex

unreal-behavior-trees — скилл для Claude Code

Скилл помогает собирать AI NPC в Unreal Engine 5 через Behavior Trees и Blackboards. Нужен для врагов, патрулей и реактивных веток поведения.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill unreal-behavior-trees -a claude-code
Открыть на GitHub

Что делает unreal-behavior-trees

Скилл описывает рабочую схему AI для Unreal Engine 5.8: Blackboard хранит ключи вроде TargetActor и LastKnownLocation, Behavior Tree задаёт логику, а AAIController запускает дерево через RunBehaviorTree(BT). Ветки строятся из Selector, Sequence и Simple Parallel.

Decorators проверяют условия Blackboard, Services обновляют состояние активной ветки, а Tasks возвращают Succeeded, Failed или InProgress. Для отладки используется Behavior Tree debugger в PIE, где видны выполняемый узел и текущие значения Blackboard. Скилл также разбирает C++-код для BTTask и обновления ключей из контроллера.

Проекту нужен Unreal Engine 5.8 и связка BT_/BB_ с AAIController. Без Nav Mesh MoveTo завершится с ошибкой, а задача, которая оставила InProgress без FinishLatentTask, повиснет. Если в проекте уже применяются StateTree, это повод проверить архитектуру до добавления Behavior Tree.

Какие задачи решает

  • собрать BT_ и BB_ для AI NPC
  • развести ветки атаки, преследования и патруля
  • связать Blackboard с AAIController
  • написать собственный BTTask или BTService
  • найти причину сбоя MoveTo или зависшей задачи

Примеры запросов агенту

  • Собери для врага Behavior Tree с приоритетом: атака по TargetActor, затем поиск в LastKnownLocation, затем патруль.
  • Напиши C++-класс BTTask для перемещения к TargetActor и корректно заверши latent-задачу.
  • Проверь, почему MoveTo сразу завершается с ошибкой, и покажи, что нужно проверить в Nav Mesh и Blackboard.

Как установить unreal-behavior-trees

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill unreal-behavior-trees -a claude-code

2Вручную: положить файлы

~/.claude/skills/unreal-behavior-trees/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/unreal-behavior-trees/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о unreal-behavior-trees

Как установить unreal-behavior-trees в Claude Code?

Выполните npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill unreal-behavior-trees -a claude-code, затем повторите эту же команду и проверьте файл ~/.claude/skills/unreal-behavior-trees/SKILL.md.

Что делает unreal-behavior-trees?

Скилл помогает проектировать AI NPC в Unreal Engine 5.8 через Behavior Trees и Blackboards: создавать ветки Selector и Sequence, добавлять Decorators, Services и Tasks, а затем запускать дерево из AAIController.

Почему Behavior Tree не реагирует на изменение Blackboard?

Проверьте Observer Aborts у Decorator. При значении None дерево не переоценивает ветку после изменения ключа; используйте Self, Lower Priority или Both по нужной логике.

Исходный текст

SKILL.md · Apache-2.0
---
name: unreal-behavior-trees
description: >
  Build NPC AI in Unreal Engine 5 with Behavior Trees and Blackboards: composites
  (Selector/Sequence), tasks, decorators, services, and running the tree from an AIController.
  Use when creating enemy/NPC AI, BT_/BB_ assets, custom BTTask or BTService nodes, or when
  the user mentions Behavior Tree, Blackboard, AIController, BTTask, decorator, or service.
---

# Unreal Behavior Trees

Author NPC decision-making in UE5 with Behavior Trees driven by a Blackboard: structure the
tree with composites, gate branches with decorators, keep state current with services, and run
it from an AIController. Targets **UE 5.8**.

## When to use

- Use when building enemy/NPC AI: creating a `BT_`/`BB_` asset pair, structuring
  Selector/Sequence branches, adding decorators (conditions) and services (periodic updates),
  writing custom `BTTask`/`BTService` nodes, or wiring an AIController to run the tree.
- Use when the project has Behavior Tree (`BT_`) and Blackboard (`BB_`) assets and an
  `AAIController`.

**When *not* to use:** the *concept* of AI (FSM vs BT vs steering, cross-engine) →
`game-ai`. Pure navigation/pathing math is engine navmesh (BT's `MoveTo` uses it). Simple
one-off logic may be cheaper as a small state machine than a full tree.

**Behavior Tree or StateTree?** UE 5.8 ships both, and Behavior Trees are not deprecated.
StateTree is Epic's general-purpose hierarchical state machine: it combines BT-style
selection with explicit States and Transitions. If the project already uses StateTree
assets, or the AI is naturally a set of modes with clear transitions (patrol → alert →
combat), check with the user before adding a Behavior Tree next to it. Keep using Behavior
Trees where the project already has `BT_`/`BB_` assets.

## Core workflow

1. **Create the pair:** a Blackboard (`BB_`) holds typed keys (the AI's memory: `TargetActor`,
   `LastKnownLocation`, `bIsInvestigating`); a Behavior Tree (`BT_`) references that Blackboard.
2. **Possess and run.** An `AAIController` possesses the pawn and calls `RunBehaviorTree(BT)`,
   which also initializes the referenced Blackboard.
3. **Structure with composites.** **Selector** runs children left→right until one *succeeds*
   (priority/fallback: "attack, else chase, else patrol"). **Sequence** runs children until one
   *fails* (do-all: "move to cover → reload → peek"). **Simple Parallel** runs one main task
   alongside a secondary.
4. **Gate branches with Decorators** that read Blackboard keys (e.g. "Has Target?" guards the
   combat branch). Set **Observer Aborts** so the tree re-evaluates when the key changes.
5. **Keep the Blackboard current with Services** attached to a branch — they tick periodically
   (e.g. update `TargetActor` via a sight check) only while that branch is active.
6. **Do work in Tasks**, which return `Succeeded`, `Failed`, or `InProgress` (latent tasks like
   `MoveTo` finish later).
7. **Verify** with the Behavior Tree debugger during PIE — it highlights the running node and
   shows live Blackboard values, so you see exactly which branch executes.

## Patterns

### 1. AIController that runs the tree (C++)

```cpp
void AEnemyAIController::OnPossess(APawn* InPawn)
{
    Super::OnPossess(InPawn);
    if (BehaviorTree)                 // UPROPERTY(EditAnywhere) TObjectPtr<UBehaviorTree>
        RunBehaviorTree(BehaviorTree); // initializes & uses the Blackboard the BT references
}
```

### 2. A priority tree (node structure)

```text
ROOT
└── Selector (try combat, else investigate, else patrol)
    ├── Sequence            [Decorator: Blackboard 'TargetActor' Is Set, Observer Aborts: Both]
    │     ├── Task: MoveTo (TargetActor)          // latent: returns InProgress then Succeeded
    │     └── Task: Attack
    ├── Sequence            [Decorator: 'LastKnownLocation' Is Set]
    │     ├── Task: MoveTo (LastKnownLocation)
    │     └── Task: Wait (3s) + clear key
    └── Task: Patrol (BTTask_FindPatrolPoint -> MoveTo)
```

`Observer Aborts: Both` makes the combat branch interrupt patrol the instant `TargetActor` is
set, and bail out when it's cleared — this is what makes the AI feel reactive.

### 3. Updating the Blackboard from code (e.g. on seeing the player)

```cpp
void AEnemyAIController::SetTarget(AActor* Target)
{
    if (UBlackboardComponent* BB = GetBlackboardComponent())
        BB->SetValueAsObject(TEXT("TargetActor"), Target);   // key name must match the BB asset
}
// Clear with BB->ClearValue(TEXT("TargetActor")); to drop back to a lower-priority branch.
```

## Pitfalls

- **AI never starts** — the pawn isn't possessed (set the Pawn's *Auto Possess AI* to "Placed
  in World or Spawned" and assign the AIController), or `RunBehaviorTree` was never called.
- **`MoveTo` instantly fails** — no NavMesh in the level (add a Nav Mesh Bounds Volume), or the
  target is off the navmesh.
- **Branch doesn't react to changes** — the gating Decorator's **Observer Aborts** is set to
  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
  (stops on first success). Swapping them inverts the behaviour.

## References

- For a **custom C++ `UBTTaskNode`** (instant and latent `ExecuteTask` returning `EBTNodeResult`,
  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`).

## Related skills

- `game-ai` — engine-agnostic AI design (FSM, BT, steering, pathfinding choices).
- `unreal-cpp-gameplay` — the AIController and pawn classes in C++.
- `fps-shooter` / `tower-defense` — genres that compose enemy AI.

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Похожие скиллы

Всё по теме «Геймдев и 3D: Unity, Unreal, Godot, Blender» →
ue-state-trees quodsoler Скилл для работы с State Tree в Unreal Engine C++: задачи, условия, evaluators, схемы, переходы и Mass-поведения. Пригодится, когда дерево состояний надо написать или починить. CX Codex +1 1 100установок unreal-engine-cpp-pro sickn33 Скилл для разработки на C++ в Unreal Engine 5.x: правила работы с UObject, сборщиком мусора, отражением и производительностью. CX Codex +1 1 400установок unreal-engine DSTN2000 Скилл обучает ассистента исследовать структуру проекта Unreal Engine перед написанием кода. Он находит файлы .uproject, сканирует ассеты и настраивает C++, Enhanced Input или GAS. CX Codex +1 511установок unreal-engine-skills-for-claude-code Epic Games Плагин даёт Claude доступ к запущенному Unreal Editor через MCP: акторы, блюпринты, материалы, Niagara, Sequencer и другие инструменты. ★ 1 634звёзд репо game-developer https://github.com/Jeffallan Скилл для разработки игр в Unity и Unreal Engine. Помогает строить системы игровой логики, настраивать физику, многопользовательские сети, шейдеры и оптимизировать производительность до 60+ FPS. CX Codex +1 6 400установок ue-cpp-foundations quodsoler Направляет агента при написании кода C++ для Unreal Engine 5.8: помогает настроить макросы рефлексии, сборщик мусора, подсистемы и умные указатели. CX Codex +1 1 400установок

Из того же набора77

unreal-blueprints Помогает проектировать геймплейную логику на блюпринтах в Unreal Engine 5. Подсказывает, как связать графы событий и не сломать проект жёсткими ссылками при общении классов. CX Codex +1 5 300установок pygame-core Скилл собирает каркас игры на pygame: игровой цикл, движение с учётом delta-time, ввод, спрайты и коллизии. Пригодится, когда проект начинается с import pygame. CX Codex +1 5 100установок bevy-ecs Держит агента в рамках ECS-модели Bevy: плагины, компоненты и ресурсы, системы с Query. Пригодится, когда проект на Rust уже тянет bevy и пора наводить порядок в системах. CX Codex +1 5 100установок unreal-packaging Помогает собрать проект Unreal Engine 5 в готовый билд через интерфейс редактора или утилиту RunUAT. Пригодится при настройке профилей сборки, кукинге контента и подготовке релизов для CI. CX Codex +1 5 200установок unreal-niagara Скилл ведёт агента по Niagara в Unreal Engine 5: сборка систем и эмиттеров, модули в стейджах spawn/update, спавн эффектов из Blueprint и C++. CX Codex +1 5 200установок unreal-enhanced-input Помогает настроить систему ввода Enhanced Input в Unreal Engine 5. Полезен при сборке ассетов действий, привязке событий в C++ или Blueprints и отладке управления. CX Codex +1 5 200установок love2d-core Настраивает каркас игры на LÖVE 11.5: цикл love.load/update/draw, движение через dt, стек экранов и ввод. Помогает избежать рассинхронизации скорости от FPS и ошибок с цветом. CX Codex +1 5 000установок ai-behavior-trees-utility-ai Помогает реализовать деревья поведений и систему Utility AI для игровых NPC. Пригодится при создании логики ботов в Unity или Godot за пределами обычного FSM. CX Codex +1 4 900установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой