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(ai-behavior-trees-utility-ai): make the C# runtime compile and behave as described

Kiro Crew0c871ea17a8d
diff --git a/skills/disciplines/ai-behavior-trees-utility-ai/SKILL.md b/skills/disciplines/ai-behavior-trees-utility-ai/SKILL.md
index 475a03e..9c54c53 100644
--- a/skills/disciplines/ai-behavior-trees-utility-ai/SKILL.md
+++ b/skills/disciplines/ai-behavior-trees-utility-ai/SKILL.md
@@ -97,23 +97,28 @@ public abstract class Node
```csharp
// Selector = fallback/OR: return the first child that is not Failure.
+// `Current` (from Composite) remembers a Running child so the next tick resumes there.
public sealed class Selector : Composite
{
public override Status Tick(Blackboard bb, float dt)
{
- for (; _current < Children.Count; _current++)
+ for (; Current < Children.Count; Current++)
{
- var s = Children[_current].Tick(bb, dt);
- if (s != Status.Failure) return s; // Success or Running stops the scan
+ var s = Children[Current].Tick(bb, dt);
+ if (s == Status.Running) return Status.Running; // resume here next tick
+ if (s == Status.Success) { Current = 0; return Status.Success; }
}
- _current = 0;
- return Status.Failure; // every child failed
+ Current = 0;
+ return Status.Failure; // every child failed
}
}
```
-The reciprocal `Sequence` (AND — stop at first non-`Success`), `Parallel`, the `Blackboard`, the
-leaf base classes, and every decorator are in `references/behavior-tree-core.md`.
+The reciprocal `Sequence` (AND — stop at first non-`Success`), the reactive variants that let a
+higher-priority branch interrupt a running one, `Parallel`, the `Blackboard`, the leaf base
+classes, and every decorator are in `references/behavior-tree-core.md`. The leaves use Unity's
+`Vector2` member names (`magnitude`, `normalized`, `sqrMagnitude`); in Godot C# use `Length()`,
+`Normalized()` and `LengthSquared()`.
## Utility scoring in one snippet
@@ -123,8 +128,9 @@ float Score(Blackboard bb)
{
float distance01 = Curves.InverseLerp01(bb.Get<float>("distToPlayer"), 20f, 2f); // near = 1
float health01 = Curves.Sigmoid(bb.Get<float>("health01"), k: 8f, mid: 0.4f); // hurt = low
- // Product + compensation keeps a single 0 from vetoing while low values still dampen.
- return Curves.CompensatedProduct(new[] { distance01, health01 });
+ // A 0 in any factor still vetoes the action; compensation stops each extra
+ // consideration from dragging every score toward 0. No allocation per call.
+ return Curves.Compensate(distance01 * health01, count: 2);
}
```
@@ -138,6 +144,12 @@ The full curve library (linear, quadratic, exponential, logistic/sigmoid, smooth
resume where you left off; only `Reset()` a subtree when a parent actually abandons it.
- **Deep trees re-evaluated wholesale each tick** waste time and cause thrash. Prefer shallow
trees and *conditional aborts* (a higher-priority condition can interrupt a lower branch).
+- **A guard condition stops being checked once the action after it is `Running`.** A memory
+ `Sequence` resumes at the running child, so `[CanSeePlayer?, Chase]` keeps chasing after sight
+ is lost. Use a `ReactiveSequence` (re-checks from the first child each tick) or have the action
+ itself fail when its blackboard input disappears.
+- **A cooldown that clears on `Reset()`** lets an agent bypass it by flickering between branches.
+ Keep the ready-time when the branch is aborted.
- **Un-normalized considerations.** If one curve outputs 0..100 and another 0..1, the big one
dominates. Every consideration must return 0..1.
- **Utility jitter on near-ties.** Add hysteresis: give the currently-running action a small bonus
diff --git a/skills/disciplines/ai-behavior-trees-utility-ai/references/behavior-tree-core.md b/skills/disciplines/ai-behavior-trees-utility-ai/references/behavior-tree-core.md
index e42abec..0e35aac 100644
--- a/skills/disciplines/ai-behavior-trees-utility-ai/references/behavior-tree-core.md
+++ b/skills/disciplines/ai-behavior-trees-utility-ai/references/behavior-tree-core.md
@@ -1,8 +1,12 @@
# Behavior Tree core — Blackboard, nodes, leaves, composites, decorators
Depth for `ai-behavior-trees-utility-ai`. A complete, allocation-conscious C# behavior-tree
-runtime. The code targets plain C# (no engine types) so it drops into Unity 6 or Godot 4 C#
-unchanged — bind the leaves to your engine's transform/navigation in the concrete actions.
+runtime. The tree logic is plain C# with no engine types; the example leaves use a `Vector2` with
+Unity's member names (`magnitude`, `normalized`, `sqrMagnitude`), so they compile as-is in
+Unity 6. In Godot 4 C# the same leaves need `Length()`, `Normalized()` and `LengthSquared()`;
+outside an engine, `System.Numerics.Vector2` has `Length()`, `LengthSquared()` and
+`Vector2.Normalize(v)`. Bind the leaves to your engine's transform/navigation in the concrete
+actions.
Contract in one line: every node's `Tick` returns `Success`, `Failure`, or `Running`, and a
parent decides what that means. Build the tree once at spawn; keep per-tick work allocation-free.
@@ -262,9 +266,40 @@ public sealed class ReactiveSelector : Composite
}
```
-`Parallel` ticks every child each step and resolves with a policy — succeed when *any* (or *all*)
-succeed, fail when *any* (or *all*) fail. Use it for "attack while strafing" or "play VFX while
-moving".
+The reactive selector re-ticks its *children* from index 0, but a memory `Sequence` child still
+resumes at its own running action, so the condition at the front of that sequence is not
+re-checked while the action runs. When a condition must keep guarding a running action ("chase
+only while I can see the player"), use a **reactive sequence**:
+
+```csharp
+// Reactive sequence: re-checks every child from index 0 each tick. If an earlier child stops
+// succeeding, the later Running child is aborted with Reset(). Put only conditions (or cheap,
+// repeatable actions) in front of the long-running child.
+public sealed class ReactiveSequence : Composite
+{
+ private int _running = -1;
+ public override Status Tick(Blackboard bb, float dt)
+ {
+ for (int i = 0; i < Children.Count; i++)
+ {
+ var s = Children[i].Tick(bb, dt);
+ if (s == Status.Success) continue;
+ if (_running > i) Children[_running].Reset(); // an earlier child stopped us
+ _running = s == Status.Running ? i : -1;
+ return s; // Failure or Running
+ }
+ _running = -1;
+ return Status.Success;
+ }
+
+ public override void Reset() { base.Reset(); _running = -1; }
+}
+```
+
+`Parallel` ticks every unfinished child each step and resolves with a policy — succeed when *any*
+(or *all*) succeed, fail when *any* (or *all*) fail. Use it for "attack while strafing" or "play
+VFX while moving". It must remember which children already finished: re-ticking a child that
+succeeded restarts it, and `RequireAll` would then never see every child succeed on the same tick.
```csharp
public enum ParallelPolicy { RequireOne, RequireAll }
@@ -272,23 +307,43 @@ public enum ParallelPolicy { RequireOne, RequireAll }
public sealed class Parallel : Composite
{
private readonly ParallelPolicy _success, _failure;
+ private Status[] _results = System.Array.Empty<Status>(); // per-child result; Running = unfinished
+
public Parallel(ParallelPolicy success, ParallelPolicy failure)
{ _success = success; _failure = failure; }
public override Status Tick(Blackboard bb, float dt)
{
+ int n = Children.Count;
+ if (_results.Length != n) // first tick (or children changed)
+ {
+ _results = new Status[n];
+ System.Array.Fill(_results, Status.Running);
+ }
+
int successes = 0, failures = 0;
- foreach (var child in Children)
+ for (int i = 0; i < n; i++)
{
- var s = child.Tick(bb, dt);
- if (s == Status.Success) successes++;
- else if (s == Status.Failure) failures++;
+ if (_results[i] == Status.Running) _results[i] = Children[i].Tick(bb, dt);
+ if (_results[i] == Status.Success) successes++;
+ else if (_results[i] == Status.Failure) failures++;
}
- if (_failure == ParallelPolicy.RequireOne && failures > 0) return Status.Failure;
- if (_failure == ParallelPolicy.RequireAll && failures == Children.Count) return Status.Failure;
- if (_success == ParallelPolicy.RequireOne && successes > 0) return Status.Success;
- if (_success == ParallelPolicy.RequireAll && successes == Children.Count) return Status.Success;
- return Status.Running;
+
+ var outcome = Status.Running;
+ if ((_failure == ParallelPolicy.RequireOne && failures > 0) ||
+ (_failure == ParallelPolicy.RequireAll && failures == n)) outcome = Status.Failure;
+ else if ((_success == ParallelPolicy.RequireOne && successes > 0) ||
+ (_success == ParallelPolicy.RequireAll && successes == n)) outcome = Status.Success;
+ else if (successes + failures == n) outcome = Status.Failure; // all done, no policy met
+
+ if (outcome != Status.Running) Reset(); // stop children still running, clear the record
+ return outcome;
+ }
+
+ public override void Reset()
+ {
+ base.Reset(); // resets every child
+ System.Array.Fill(_results, Status.Running);
}
}
```
@@ -339,6 +394,8 @@ public sealed class Repeat : Decorator
}
// Cooldown: gate the child so it can only run once per interval (attack/ability rate-limiting).
+// No Reset() override on purpose: aborting the branch must not clear the cooldown, or an agent
+// that flickers between branches attacks every time it re-enters.
public sealed class Cooldown : Decorator
{
private readonly float _seconds;
@@ -353,8 +410,6 @@ public sealed class Cooldown : Decorator
if (s == Status.Success) _readyAt = now + _seconds;
return s;
}
-
- public override void Reset() { base.Reset(); _readyAt = 0f; }
}
```
@@ -380,10 +435,12 @@ public sealed class BehaviorTree
// Fluent assembly — build once at spawn, then tick.
var tree = new BehaviorTree(
new ReactiveSelector()
- .Add(new Sequence() // combat branch (highest priority)
- .Add(new CanSeeTarget(sightRange: 12f))
+ .Add(new ReactiveSequence() // combat branch (highest priority)
+ .Add(new CanSeeTarget(sightRange: 12f)) // re-checked every tick
.Add(new MoveToTarget(speed: 6f, arriveRadius: 1.5f))
- .Add(new Cooldown(0.8f).Wrap(new AttackTarget())))
+ // ForceSuccess: while the cooldown blocks the swing, the guard holds position
+ // instead of failing the branch and stepping back into Patrol for a tick.
+ .Add(new ForceSuccess().Wrap(new Cooldown(0.8f).Wrap(new AttackTarget()))))
.Add(new Patrol(waypoints)), // fallback
blackboard);
```
diff --git a/skills/disciplines/ai-behavior-trees-utility-ai/references/practical-examples.md b/skills/disciplines/ai-behavior-trees-utility-ai/references/practical-examples.md
index 38b1223..f444bd0 100644
--- a/skills/disciplines/ai-behavior-trees-utility-ai/references/practical-examples.md
+++ b/skills/disciplines/ai-behavior-trees-utility-ai/references/practical-examples.md
@@ -67,10 +67,10 @@ public sealed class GuardAgent
{
_tree = new BehaviorTree(
new ReactiveSelector() // reactive: seeing the player preempts patrol
- .Add(new Sequence() // --- combat branch (higher priority) ---
- .Add(new CanSeeTarget(sightRange: 12f))
+ .Add(new ReactiveSequence() // --- combat branch (higher priority) ---
+ .Add(new CanSeeTarget(sightRange: 12f)) // re-checked every tick
.Add(new MoveToTarget(speed: 6f, arriveRadius: 1.5f))
- .Add(new Cooldown(0.8f).Wrap(new AttackTarget())))
+ .Add(new ForceSuccess().Wrap(new Cooldown(0.8f).Wrap(new AttackTarget()))))
.Add(new Patrol(patrolRoute)), // --- fallback ---
_bb);
}
@@ -169,7 +169,7 @@ var attackChoice = new UtilityEvaluator()
var hybrid = new BehaviorTree(
new ReactiveSelector()
- .Add(new Sequence()
+ .Add(new ReactiveSequence() // keeps re-checking sight while attacking
.Add(new CanSeeTarget(12f))
.Add(new UtilitySelectorNode(attackChoice))) // BT picks "engage"; utility picks how
.Add(new Patrol(route)),
diff --git a/skills/disciplines/ai-behavior-trees-utility-ai/references/utility-ai-system.md b/skills/disciplines/ai-behavior-trees-utility-ai/references/utility-ai-system.md
index 0a04b55..1e14bed 100644
--- a/skills/disciplines/ai-behavior-trees-utility-ai/references/utility-ai-system.md
+++ b/skills/disciplines/ai-behavior-trees-utility-ai/references/utility-ai-system.md
@@ -23,8 +23,11 @@ public static class Curves
public static float InverseLerp01(float x, float a, float b)
=> a == b ? (x >= b ? 1f : 0f) : Clamp01((x - a) / (b - a));
- // Linear: desire tracks the fact directly.
- public static float Linear(float t, float slope = 1f, float yIntercept = 0f)
+ // Linear: desire tracks the fact directly. The one-argument overload is what lets
+ // `Curves.Linear` be passed as a Func<float, float>: optional parameters do not count
+ // for method-group conversion, so a single method with defaults would not compile there.
+ public static float Linear(float t) => Clamp01(t);
+ public static float Linear(float t, float slope, float yIntercept)
=> Clamp01(slope * t + yIntercept);
// Polynomial: exponent>1 = ease-in (low until high t); exponent<1 = ease-out (rises fast early).
@@ -45,6 +48,15 @@ public static class Curves
// Smoothstep: eased 0..1 with zero slope at both ends; good default for "soft threshold".
public static float Smoothstep(float t) { t = Clamp01(t); return t * t * (3f - 2f * t); }
+
+ // Compensation for a product of `count` factors (see "Scored actions" below).
+ public static float Compensate(float product, int count)
+ {
+ if (count <= 1) return Clamp01(product);
+ float modFactor = 1f - 1f / count; // 0 for one factor, -> 1 as count grows
+ float makeUp = (1f - product) * modFactor;
+ return Clamp01(product + makeUp * product); // a 0 product stays 0 (still a veto)
+ }
}
```
@@ -109,12 +121,8 @@ public sealed class UtilityAction
float product = 1f;
for (int i = 0; i < n; i++) product *= Considerations[i].Evaluate(bb);
- // Compensation: add back some of what extra factors removed. modFactor -> 0 as n grows.
- float modFactor = 1f - 1f / n;
- float makeUp = (1f - product) * modFactor;
- float compensated = product + makeUp * product;
-
- return Weight * Curves.Clamp01(compensated);
+ // Compensation: add back some of what extra factors removed (Curves.Compensate).
+ return Weight * Curves.Compensate(product, n);
}
}
```
@@ -149,13 +157,21 @@ public sealed class UtilityEvaluator
}
// Softmax: choose proportionally to exp(score/temperature). Higher temp = more random.
+ // Subtract the best score before exp(): with a small temperature, exp(score / 0.01)
+ // overflows float to infinity and the roll stops working. The result is unchanged.
public UtilityAction SelectSoftmax(Blackboard bb, System.Random rng, float temperature = 0.2f)
{
- float sum = 0f;
- var weights = new float[_actions.Count];
+ var weights = new float[_actions.Count]; // allocate once as a field on hot paths
+ float maxScore = float.NegativeInfinity;
for (int i = 0; i < _actions.Count; i++)
{
- weights[i] = System.MathF.Exp(_actions[i].Score(bb) / System.MathF.Max(temperature, 1e-4f));
+ weights[i] = _actions[i].Score(bb);
+ if (weights[i] > maxScore) maxScore = weights[i];
+ }
+ float t = System.MathF.Max(temperature, 1e-4f), sum = 0f;
+ for (int i = 0; i < weights.Length; i++)
+ {
+ weights[i] = System.MathF.Exp((weights[i] - maxScore) / t);
sum += weights[i];
}
float roll = (float)rng.NextDouble() * sum;