quot;{mark}{actions[i].id}: {brain.Reasoner.Scores[i]:0.00}{cd}"); } UnityEditor.Handles.Label(transform.position + Vector3.up * height, _text.ToString()); } #endif } ``` With **Gizmos** on, every guard shows its actions and last scores above its head, with `>` beside the running one and `(cooldown)` beside any that are cooling down. Turn on Gizmos in the Game view too to watch while you play. Combined with the blackboard's **Visible** list (part 5), you can always answer "why did it do that?": find the fact, then the consideration, then the curve. ## 6.2 A tuning workflow 1. **Write the behaviour you want as sentences.** "The guard fights while above about 30 % health, runs when lower, and heals only after losing sight of the player for a few seconds." 2. **Set up situations** and check which action wins. You can do this without Play mode: give a `DictionaryContext` the facts and call `Decide`. Here is the guard's action set from part 5 in nine situations (real output, momentum 0): | Situation | Winner | Notable scores | |---|---|---| | Healthy, sees player at 8 m | Attack | Attack 0.94 | | Healthy, sees player at 28 m | Attack | Attack 0.62 | | Sees player at 10 m, no ammo | Reload | Reload 0.96 | | No ammo, player 25 m away | Reload | Reload 1.20 | | 20 % health, sees player | Flee | Flee 0.96, Attack 0.31 | | 40 % health, alone, lost player 8 s ago | Heal | Heal 0.75, Investigate 0.58, Patrol 0.25 | | Full health, lost player 2 s ago | Investigate | Investigate 0.76 | | Nothing happening | Patrol | Patrol 0.25 | | 50 % health, half ammo, player at 10 m | Attack | Attack 0.88, Reload 0.30, Flee 0.27 | 3. **Change one curve at a time** and re-run the situations. Keep them as tests (next section) so a later tweak can't quietly break an earlier one. 4. **Then play.** Numbers that look right in a table can still feel wrong at speed. Watch the overlay. ## 6.3 Tests Put the three pure files in a folder with their own assembly definition, or leave them in `Assembly-CSharp`, and add an Edit Mode test assembly as shown in [[Unity Test Framework]]: **`UtilityTests.cs`** ```csharp using System.Collections.Generic; using NUnit.Framework; public class UtilityTests { static Consideration C(string input, ResponseCurve curve, float min = 0f, float max = 1f) => new Consideration { name = input, input = input, min = min, max = max, curve = curve }; static UtilityAction A(string id, params Consideration[] cs) => new UtilityAction { id = id, considerations = new List<Consideration>(cs) }; [Test] public void CurvesHitTheirKnownPoints() { Assert.AreEqual(0.3f, ResponseCurve.Linear().Evaluate(0.3f), 1e-5f); Assert.AreEqual(0.7f, ResponseCurve.Linear().Inverted().Evaluate(0.3f), 1e-5f); Assert.AreEqual(0.25f, ResponseCurve.Polynomial(2f).Evaluate(0.5f), 1e-5f); Assert.AreEqual(0.5f, ResponseCurve.Logistic(10f, 0.5f).Evaluate(0.5f), 1e-5f); Assert.AreEqual(0.5f, ResponseCurve.Logit().Evaluate(0.5f), 1e-5f); Assert.AreEqual(0f, ResponseCurve.Step(0.6f).Evaluate(0.59f)); Assert.AreEqual(1f, ResponseCurve.Step(0.6f).Evaluate(0.6f)); } [Test] public void CurvesStayInZeroToOne() { var curves = new[] { ResponseCurve.Linear(3f, -0.5f), ResponseCurve.Polynomial(0.5f), ResponseCurve.Logistic(30f), ResponseCurve.Logit(1f), ResponseCurve.Constant(2f) }; foreach (var c in curves) for (var x = -0.5f; x <= 1.5f; x += 0.05f) { var y = c.Evaluate(x); Assert.IsTrue(y >= 0f && y <= 1f, c.type + " at " + x + " = " + y); } Assert.AreEqual(0f, ResponseCurve.Linear().Evaluate(float.NaN)); } [Test] public void ConsiderationNormalizesRawRange() { var ctx = new DictionaryContext { ["threat_distance"] = 15f }; var near = C("threat_distance", ResponseCurve.Linear().Inverted(), 0f, 20f); Assert.AreEqual(0.25f, near.Score(ctx), 1e-5f); ctx["threat_distance"] = 40f; Assert.AreEqual(0f, near.Score(ctx), 1e-5f); } [Test] public void MissingInputUsesMissingScore() { var c = C("nothing", ResponseCurve.Linear()); Assert.AreEqual(0f, c.Score(new DictionaryContext())); c.missingScore = 0.4f; Assert.AreEqual(0.4f, c.Score(new DictionaryContext()), 1e-6f); } [Test] public void CompensationLiftsManyConsiderations() { Assert.AreEqual(0.6786f, UtilityScoring.Compensate(0.512f, 3), 1e-3f); Assert.AreEqual(0.9f, UtilityScoring.Compensate(0.9f, 1), 1e-6f); var ctx = new DictionaryContext { ["a"] = 0.8f, ["b"] = 0.8f, ["c"] = 0.8f }; var three = A("x", C("a", ResponseCurve.Linear()), C("b", ResponseCurve.Linear()), C("c", ResponseCurve.Linear())); Assert.IsTrue(UtilityScoring.Score(three, ctx) > 0.512f + 0.1f); } [Test] public void AnyZeroVetoes() { var ctx = new DictionaryContext { ["a"] = 1f, ["b"] = 0f }; var action = A("x", C("a", ResponseCurve.Linear()), C("b", ResponseCurve.Linear())); var breakdown = new float[2]; Assert.AreEqual(0f, UtilityScoring.Score(action, ctx, breakdown)); Assert.AreEqual(1f, breakdown[0]); } [Test] public void WeightScalesScore() { var ctx = new DictionaryContext { ["a"] = 0.5f }; var action = A("x", C("a", ResponseCurve.Linear())); action.weight = 2f; Assert.AreEqual(1f, UtilityScoring.Score(action, ctx), 1e-6f); } static (List<UtilityAction>, DictionaryContext) Guard() { var attack = A("Attack", C("threat_visible", ResponseCurve.Step(0.5f)), C("health", ResponseCurve.Logistic(12f, 0.3f))); var flee = A("Flee", C("threat_visible", ResponseCurve.Step(0.5f)), C("health", ResponseCurve.Polynomial(3f).Inverted())); flee.weight = 1.5f; var patrol = A("Patrol", C("threat_visible", ResponseCurve.Step(0.5f).Inverted())); patrol.weight = 0.3f; return (new List<UtilityAction> { attack, flee, patrol }, new DictionaryContext { ["threat_visible"] = 1f, ["health"] = 1f }); } [Test] public void GuardAttacksHealthyFleesHurtPatrolsAlone() { var (actions, ctx) = Guard(); var r = new UtilityReasoner(actions) { Momentum = 0f }; Assert.AreEqual(0, r.Decide(ctx, 0)); ctx["health"] = 0.1f; Assert.AreEqual(1, r.Decide(ctx, 1)); ctx["threat_visible"] = 0f; Assert.AreEqual(2, r.Decide(ctx, 2)); } [Test] public void MomentumPreventsFlicker() { var a = A("a", C("x", ResponseCurve.Linear())); var b = A("b", C("x", ResponseCurve.Linear().Inverted())); var ctx = new DictionaryContext { ["x"] = 0.55f }; var r = new UtilityReasoner(new List<UtilityAction> { a, b }) { Momentum = 0.25f }; Assert.AreEqual(0, r.Decide(ctx, 0)); ctx["x"] = 0.48f; // b now slightly better (0.52 vs 0.48*1.25 = 0.60) Assert.AreEqual(0, r.Decide(ctx, 1)); ctx["x"] = 0.3f; // b clearly better (0.7 vs 0.375) Assert.AreEqual(1, r.Decide(ctx, 2)); } [Test] public void CommitHoldsActionUntilTimeOrVeto() { var a = A("a", C("x", ResponseCurve.Linear())); a.commitSeconds = 2f; var b = A("b", C("x", ResponseCurve.Linear().Inverted())); var ctx = new DictionaryContext { ["x"] = 0.9f }; var r = new UtilityReasoner(new List<UtilityAction> { a, b }) { Momentum = 0f }; r.Decide(ctx, 0); ctx["x"] = 0.1f; Assert.AreEqual(0, r.Decide(ctx, 1)); Assert.AreEqual(1, r.Decide(ctx, 2.5)); ctx["x"] = 0.9f; r.Decide(ctx, 3); // back to a, committed ctx["x"] = 0f; // a scores 0: commitment can't hold a vetoed action Assert.AreEqual(1, r.Decide(ctx, 3.5)); } [Test] public void CooldownStartsWhenActionEnds() { var a = A("a"); a.cooldownSeconds = 5f; var b = A("b"); b.weight = 0.1f; var r = new UtilityReasoner(new List<UtilityAction> { a, b }); var ctx = new DictionaryContext(); Assert.AreEqual(0, r.Decide(ctx, 0)); r.EndCurrent(1); Assert.AreEqual(1, r.Decide(ctx, 2)); Assert.IsTrue(r.OnCooldown(0, 5.9)); Assert.AreEqual(0, r.Decide(ctx, 6.1)); } [Test] public void NothingAboveZeroReturnsMinusOne() { var r = new UtilityReasoner(new List<UtilityAction> { A("a", C("x", ResponseCurve.Linear())) }); Assert.AreEqual(-1, r.Decide(new DictionaryContext { ["x"] = 0f }, 0)); } [Test] public void WeightedRandomPicksOnlyCloseContendersInProportion() { var a = A("a"); a.weight = 1f; var b = A("b"); b.weight = 0.9f; var c = A("c"); c.weight = 0.2f; // below 80 % of best: never picked var counts = new int[3]; var r = new UtilityReasoner(new List<UtilityAction> { a, b, c }, new System.Random(42)) { Selection = UtilitySelection.WeightedRandomAmongTop, Momentum = 0f }; for (var i = 0; i < 2000; i++) { counts[r.Decide(new DictionaryContext(), i)]++; r.EndCurrent(i); } Assert.AreEqual(0, counts[2]); Assert.IsTrue(counts[0] > 900 && counts[0] < 1200, "a=" + counts[0]); Assert.IsTrue(counts[1] > 800 && counts[1] < 1100, "b=" + counts[1]); } } ``` | Test | Proves | |---|---| | CurvesHitTheirKnownPoints | Each curve type's formula | | CurvesStayInZeroToOne | Output is clamped for out-of-range input and extreme parameters; NaN becomes 0 | | ConsiderationNormalizesRawRange | Raw range to 0..1, clamped | | MissingInputUsesMissingScore | Unknown facts veto by default | | CompensationLiftsManyConsiderations | 0.512 becomes 0.679 for three considerations | | AnyZeroVetoes | One zero gives 0; breakdown is filled | | WeightScalesScore | Weights multiply | | GuardAttacksHealthyFleesHurtPatrolsAlone | A small end-to-end decision set | | MomentumPreventsFlicker | Close challengers don't cause a switch; clear winners do | | CommitHoldsActionUntilTimeOrVeto | Commitment holds, and a veto breaks it | | CooldownStartsWhenActionEnds | Cooldown timing | | NothingAboveZeroReturnsMinusOne | No action is better than a bad one | | WeightedRandomPicksOnlyCloseContendersInProportion | Random choice stays among good options, in proportion | All 13 pass outside Unity (.NET 10 with an NUnit stand-in) and compile against Unity's NUnit. They haven't been run in the Unity Test Runner. ## 6.4 Pitfalls 1. **Too many considerations per action.** Three or four is plenty. Each one is another thing to tune, and compensation only partly offsets the cost. 2. **Using low scores where you mean "never".** If an action must not happen, gate it with a Step curve so it scores 0. 3. **Raw values not normalized.** A distance of 15 fed straight into a curve clamps to 1. Every consideration needs a sensible `min` and `max`. 4. **Everything at weight 1.** Fillers (Patrol, Idle) need low weights or they compete with real actions. 5. **No momentum.** Agents flicker between two close actions. Start at 0.25. 6. **Endless loops.** Investigate, find nothing, investigate again. Give such actions a cooldown. 7. **Behaviours that make decisions.** Keep "should I?" in considerations and "how?" in behaviours, or you'll have two places to debug. 8. **Sensors in considerations.** Raycasts inside scoring run once per action per decision. Sense once, store facts, score from facts. 9. **Deciding every frame.** Four times a second is enough; stagger agents. 10. **Optimal but unreadable enemies.** Players need to see why an enemy acts. Add tells (a shout before fleeing, a reload animation) and avoid twitchy switching. [[Level Up! (Review)]] puts fairness and readability first for enemy design. 11. **Mismatched ids.** The brain warns at startup when an action has no behaviour; read the Console. ## 6.5 Going further - Tune weights live with [[Remote Config and Live Tuning]]. - Give the reasoner a "target" dimension: score Attack once per visible enemy and pick the best action-target pair. - Let a squad share a blackboard for facts like "someone is already flanking". - Combine with [[Unity Behavior]] graphs for long scripted sequences, as described in part 1. - [[Game Programming Patterns (Review)]]: the Strategy and Component chapters map onto the behaviour components used here. Back to [[Utility AI]].