Modular Utility AI runtime engine and UI Toolkit workbench for Unity 6. It pairs a pure-C# scoring engine (UtilityScorer and UtilityBrainRunner) with a UtilityAIAgent component, parametric response curves, a typed Blackboard, an EditMode What-If Simulator, and a Play Mode Live Runtime Debugger with JSON/CSV trace export.
- Parametric response curves (
ResponseCurve): Maps normalized[0..1]inputs to[0..1]utility scores usingLinear,Polynomial,Logistic,Logit,Step, orCustomAnimationCurve, with optionalInvert(1 - y) and NaN/Infinity clamping. - Compensated scoring and reducers (
UtilityScorer): Aggregates multiple considerations using Dave Mark'sCompensatedProduct(preventing score decay on behaviors with more considerations), plusRawProduct,Average,Minimum, andMaximum. - Decision policies and anti-thrashing (
UtilityBrainAsset): SupportsHighestScore,WeightedTopK, andSoftmaxTemperaturecandidate selection alongside per-behaviorCooldownSeconds,MinCommitmentSeconds,InertiaBonus,MinSwitchDelta, and per-considerationCanVetodisqualification. - Case-insensitive typed Blackboard (
UtilityBlackboard): Storesfloat,int,bool,string,Vector3, andUnityEngine.Objectfacts withOnKeyChangednotifications, automaticinttofloatfallback inTryGetFloat, and sortedCaptureDebugEntries()snapshots. - TypeCache auto-discovery: Any non-abstract, non-generic
[Serializable]subclass ofUtilityConsiderationBaseorUtilityActionBaseappears automatically in the Workbench consideration and action menus via[SerializeReference]. - Three-tab UI Toolkit Workbench (
Tools > HaruChanZ64 > AI > UtilityAIEngine > Utility AI Workbench):- Authoring & Curves: Edit brain policy, behaviors, actions, considerations, and
ResponseCurveparameters with aPainter2Dcurve plot (ResponseCurveGraphElement) and live X-input probe. - What-If Simulator: Auto-generates sliders and toggles for referenced
BlackboardFloatConsiderationandBlackboardBoolConsiderationkeys so you can test rankings in Edit Mode without entering Play Mode. - Live Runtime Debugger: Inspect enabled Play Mode
UtilityAIAgentinstances with ranked score bars, per-considerationraw -> norm -> curvereadouts, live Blackboard view, Pause/Step controls, bounded ring-buffer tick scrubbing, and JSON/CSV export (UtilityDecisionExporter).
- Authoring & Curves: Edit brain policy, behaviors, actions, considerations, and
- Custom Inspectors and Scene gizmos:
UtilityBrainAssetInspectoradds an Open in Utility AI Workbench button,UtilityAIAgentInspectoradds Open Live Runtime Debugger plus a Play Mode active-behavior banner, andUtilityAIAgentdraws a target line and wire sphere when selected.
- Unity
6000.0or newer - Zero required external dependencies
- Open Window > Package Manager in Unity 6 (
6000.0+). - Click + (top-left) and choose Install package from git URL....
- Enter:
https://github.com/haruchanz64/UtilityAIEngine.git
Add the package path to Packages/manifest.json:
{
"dependencies": {
"com.haruchanz64.utility-ai-engine": "file:../Plugins/UtilityAIEngine"
}
}- Open Tools > HaruChanZ64 > AI > UtilityAIEngine > Utility AI Workbench and click New Brain (or create an asset via Assets > Create > UtilityAIEngine > Utility Brain).
- To inspect a complete four-behavior example right away, import the Survival Guard AI Demo sample from Package Manager and run Tools > HaruChanZ64 > AI > UtilityAIEngine > Create Survival Guard Demo Brain.
- In Authoring & Curves, add behaviors, assign a
UtilityActionBase, add considerations, and tune eachResponseCurveusing the livePainter2Dpreview andPreview Input Xslider. - Switch to What-If Simulator to drag Blackboard sliders and toggles in Edit Mode and verify which behavior wins across edge cases.
- Attach
UtilityAIAgent(fromUtilityAIEngine.Runtime.Components) to a scene GameObject, assign yourUtilityBrainAsset, and optionally seed Initial Blackboard Facts (initialFloatsandinitialBools) or assignDefault Target. - Enter Play Mode and open Live Runtime Debugger (or click Open Live Runtime Debugger in the
UtilityAIAgentInspector) to inspect live ticks, pause/step execution, scrub history, or export JSON/CSV traces.
Each evaluation in UtilityScorer.Evaluate(...) inspects every UtilityBehaviorDefinition in the UtilityBrainAsset in four stages:
- Eligibility and target resolution: Disabled behaviors and behaviors on cooldown (
context.GetCooldownRemaining(behavior.Id) > 0.0001f) are immediately disqualified with a reason string. If anIUtilityTargetProvideris present andbehavior.TargetKeyis non-empty,context.Targetis temporarily resolved for that behavior and restored after scoring. - Considerations and veto: Each consideration runs
SampleNormalizedInput(context, out rawValue)and passes the clamped[0..1]result throughResponseCurve.Evaluate(...). IfCanVetois true and the curve output is<= 0.0001, the entire behavior is disqualified (Vetoed by <Name>). Behaviors with no considerations receive a baseline utility of1.0. - Aggregation, weight, and inertia: Consideration outputs are reduced via
ScoreAggregationMode(CompensatedProduct,RawProduct,Average,Minimum, orMaximum). The final score ismax(0, aggregated * max(0, Weight) + inertiaBonus), whereInertiaBonusis added only to the currently active behavior. - Selection and anti-thrashing: If the active behavior has not finished its
MinCommitmentSeconds, it stays locked. Otherwise, eligible candidates (FinalScore > 0) are selected viaHighestScore,WeightedTopK, orSoftmaxTemperature. When switching away from an active, still-eligible behavior, the challenger must beat the active score by at leastMinSwitchDelta.
UtilityBrainRunner.Tick(deltaTime, forceEvaluate) advances context.ElapsedTime, re-evaluates whenever EvaluationInterval elapses (or when no behavior is active or forceEvaluate is true), and ticks the active behavior's UtilityActionBase:
OnEnter(context)runs once when a behavior becomes active.OnTick(context)runs every tick while active and returnsUtilityActionStatus.Running,Completed, orFailed.- Returning
CompletedorFailedimmediately callsOnExit(context), appliesCooldownSecondsonUtilityContext, clears the active behavior, and resets the evaluation timer so the nextTickpicks a new behavior immediately. - Calling
UtilityBrainRunner.Stop()(also called byUtilityAIAgent.OnDisable) invokesOnExit(context)without starting a cooldown.
UtilityBlackboard uses case-insensitive keys (StringComparer.OrdinalIgnoreCase) separated by storage type (float, int, bool, string, Vector3, and UnityEngine.Object). TryGetFloat and GetFloat fall back to integer entries with the same key so numeric considerations can read integer counters without duplicating facts. TryGetObject<T> checks Unity's native object lifetime so destroyed scene objects are never returned.
Subclass UtilityConsiderationBase with [Serializable]. The Workbench discovers it automatically via TypeCache:
using System;
using UnityEngine;
using UtilityAIEngine.Runtime.Core;
[Serializable]
public sealed class StaminaRatioConsideration : UtilityConsiderationBase
{
public string StaminaKey = "Stamina";
public float MaxStamina = 100f;
public override string DisplayName => string.IsNullOrWhiteSpace(Label) ? "StaminaRatio" : Label;
public override float SampleNormalizedInput(UtilityContext context, out float rawValue)
{
rawValue = context?.Blackboard != null
? context.Blackboard.GetFloat(StaminaKey, MaxStamina)
: MaxStamina;
return MaxStamina > 0.001f ? Mathf.Clamp01(rawValue / MaxStamina) : 0f;
}
}Subclass UtilityActionBase with [Serializable] and store per-agent mutable state on context.Blackboard when multiple agents share one UtilityBrainAsset:
using System;
using UnityEngine;
using UtilityAIEngine.Runtime.Core;
[Serializable]
public sealed class ReloadWeaponAction : UtilityActionBase
{
public string AmmoKey = "Ammo";
public float MaxAmmo = 30f;
public float ReloadSeconds = 1.5f;
private const string TimerKey = "_ReloadElapsed";
public override void OnEnter(UtilityContext context)
{
context?.Blackboard?.SetFloat(TimerKey, 0f);
}
public override UtilityActionStatus OnTick(UtilityContext context)
{
if (context?.Blackboard == null)
return UtilityActionStatus.Failed;
var elapsed = context.Blackboard.GetFloat(TimerKey, 0f) + context.DeltaTime;
context.Blackboard.SetFloat(TimerKey, elapsed);
if (elapsed < ReloadSeconds)
return UtilityActionStatus.Running;
context.Blackboard.SetFloat(AmmoKey, MaxAmmo);
return UtilityActionStatus.Completed;
}
public override void OnExit(UtilityContext context)
{
context?.Blackboard?.Remove(TimerKey);
}
}Attach a component implementing IUtilityTargetProvider to the same GameObject as UtilityAIAgent. UtilityAIAgent.InitializeRunner discovers it automatically via GetComponent<IUtilityTargetProvider>():
using UnityEngine;
using UtilityAIEngine.Runtime.Components;
using UtilityAIEngine.Runtime.Core;
[RequireComponent(typeof(UtilityAIAgent))]
public sealed class GuardSensors : MonoBehaviour, IUtilityTargetProvider
{
[SerializeField] private Transform threatTarget;
[SerializeField] private Transform coverPoint;
private UtilityAIAgent _agent;
private void Awake()
{
_agent = GetComponent<UtilityAIAgent>();
_agent.onBehaviorChanged.AddListener(id => Debug.Log($"Guard switched to: {id}"));
}
private void Update()
{
if (_agent.Blackboard == null) return;
_agent.Blackboard.SetBool("HasTarget", threatTarget != null);
if (threatTarget != null)
{
_agent.SetTarget(threatTarget);
}
}
public Transform ResolveTarget(UtilityContext context, string targetKey)
{
return targetKey switch
{
"Threat" => threatTarget,
"Cover" => coverPoint,
_ => threatTarget
};
}
}Use UtilityBrainRunner directly without a MonoBehaviour for simulations, server ticks, or EditMode tests:
using UtilityAIEngine.Runtime.Core;
using UtilityAIEngine.Runtime.Data;
using UtilityAIEngine.Runtime.Engine;
public static class HeadlessSimulationExample
{
public static DecisionSnapshot RunStep(UtilityBrainAsset brain, float health, bool hasTarget)
{
var context = new UtilityContext();
context.Blackboard.SetFloat("Health", health);
context.Blackboard.SetBool("HasTarget", hasTarget);
var runner = new UtilityBrainRunner(brain, context, historyCapacity: 64, randomSeed: 42);
runner.Tick(deltaTime: 0.2f, forceEvaluate: true);
return runner.LatestSnapshot;
}
}In Editor scripts, pass runner.History.ToChronologicalList() to UtilityDecisionExporter.ToJson(...) or UtilityDecisionExporter.ToCsv(...) (namespace UtilityAIEngine.Editor.Export).
| Type | Namespace | Purpose | Built-in implementation |
|---|---|---|---|
UtilityConsiderationBase |
UtilityAIEngine.Runtime.Core |
Base class for normalized [0..1] input sampling and curve evaluation |
BlackboardFloatConsideration, BlackboardBoolConsideration, DistanceToTargetConsideration, CooldownReadinessConsideration, RandomNoiseConsideration, ConstantConsideration |
UtilityActionBase |
UtilityAIEngine.Runtime.Core |
Executable behavior action lifecycle (OnEnter, OnTick, OnExit) |
WaitAction, SetBlackboardFloatAction, DeltaBlackboardFloatAction, SetBlackboardBoolAction, MoveTowardsTargetAction, LogDebugAction |
IUtilityTargetProvider |
UtilityAIEngine.Runtime.Core |
Resolves per-behavior TargetKey strings to a Transform during scoring and execution |
Implement on a sibling MonoBehaviour or pass to UtilityBrainRunner |
ResponseCurve |
UtilityAIEngine.Runtime.Core |
Parametric [0..1] -> [0..1] curve evaluator with inversion and clamping |
Linear, Polynomial, Logistic, Logit, Step, CustomAnimationCurve |
UtilityBlackboard |
UtilityAIEngine.Runtime.Core |
Case-insensitive typed fact storage with change events and debug snapshots | UtilityBlackboard |
UtilityContext |
UtilityAIEngine.Runtime.Core |
Shared evaluation context holding agent, target, timing, blackboard, and cooldowns | UtilityContext |
UtilityBrainAsset |
UtilityAIEngine.Runtime.Data |
ScriptableObject holding behaviors, selection mode, cadence, and hysteresis | UtilityBrainAsset |
UtilityBehaviorDefinition |
UtilityAIEngine.Runtime.Data |
Serializable behavior record with weight, cooldown, commitment lock, considerations, and action | UtilityBehaviorDefinition |
UtilityScorer |
UtilityAIEngine.Runtime.Engine |
Pure-C# scorer implementing compensated aggregation, vetoes, hysteresis, and selection | UtilityScorer |
UtilityBrainRunner |
UtilityAIEngine.Runtime.Engine |
Stateful cadence runner managing active action lifecycle and DecisionRingBuffer history |
UtilityBrainRunner |
UtilityAIAgent |
UtilityAIEngine.Runtime.Components |
Scene MonoBehaviour driving a brain, registering for live debugging, and drawing target gizmos |
UtilityAIAgent |
UtilityDecisionExporter |
UtilityAIEngine.Editor.Export |
Serializes DecisionSnapshot histories to JSON or RFC 4180 CSV |
UtilityDecisionExporter |
Import Survival Guard AI Demo (Samples~/SurvivalGuardDemo) from the Package Manager Samples tab:
MissingHealthRatioConsideration: TypeCache-discovered custom consideration computing(MaxHealth - Health) / MaxHealthfor heal and flee curves.ConsumeMedkitAction: TypeCache-discovered custom action with a cast timer (CastTime) that checks medkit count, restores health on the Blackboard, and decrements medkits on completion.GuardBrainDemoGenerator: Editor menu item (Tools > HaruChanZ64 > AI > UtilityAIEngine > Create Survival Guard Demo Brain) that generates a four-behaviorUtilityBrainAsset(Attack Target,Use Medkit,Flee Threat,Patrol Area) and opens it in the Workbench.
The package includes EditMode NUnit tests under Tests/Editor/ runnable from Window > General > Test Runner (EditMode tab):
Tests/Editor/ResponseCurveAndBlackboardTests.cs: verifies all parametricResponseCurveshapes, inversion, NaN/range clamping, case-insensitiveUtilityBlackboardstorage with int-to-float reading,OnKeyChangedevents, debug entry capture, key removal, and chronological wrapping inDecisionRingBuffer.Tests/Editor/UtilityScorerAndRunnerTests.cs: verifiesCompensatedProductvs.RawProductandAverageaggregation, veto/cooldown/inertia hysteresis inUtilityScorer, actionOnEnter/OnTick/OnExitlifecycle withMinCommitmentSecondslocks and post-completion cooldowns inUtilityBrainRunner, and JSON/CSV trace output inUtilityDecisionExporter.
- Custom considerations or actions do not appear in Workbench menus: Subclasses of
UtilityConsiderationBaseandUtilityActionBasemust be non-abstract, non-generic, and marked[Serializable]soTypeCachediscovers them and Unity can serialize them via[SerializeReference]. - Multiple agents sharing one
UtilityBrainAssetwith stateful actions:UtilityBehaviorDefinition.Actioninstances live directly inside theUtilityBrainAssetScriptableObject. Built-in timed actions such asWaitAction(and the sampleConsumeMedkitAction) store_elapsedon the action instance; if multipleUtilityAIAgentinstances run the same asset concurrently, either instantiate a runtime clone (Instantiate(brainAsset)) per agent or store per-agent timers oncontext.Blackboard. - What-If Simulator does not show custom consideration inputs automatically: The simulator auto-detects keys from
BlackboardFloatConsiderationandBlackboardBoolConsiderationonly. For custom float keys, use Add Virtual Fact in the simulator pane. Because the simulator runs without a sceneAgentTransformorIUtilityTargetProvider,DistanceToTargetConsiderationfalls back toDistanceWhenMissingTarget. - Commitment locks end early when an action finishes:
MinCommitmentSecondsblocks preemption by competing behaviors during periodic re-evaluations, but if the active action returnsCompletedorFailed,UtilityBrainRunnerexits it immediately, starts its cooldown, and re-evaluates on the next tick. - Live Runtime Debugger shows no active agents: Agents register in
UtilityAIAgent.ActiveAgentsduringOnEnablein Play Mode and unregister inOnDisable. Confirm the GameObject and component are enabled in Play Mode and have aUtilityBrainAssetassigned. Live updates refresh roughly every0.15swhile unpaused and viewing the latest tick. UtilityBlackboard.Clear()does not triggerOnKeyChanged: OnlySet*andRemoveraiseOnKeyChanged;Clear()silently empties all backing dictionaries.- Cooldowns are not applied when stopping an agent manually:
UtilityBrainRunner.Stop()(also invoked byUtilityAIAgent.OnDisable) callsOnExitwithout startingCooldownSeconds, whereas normal completion, failure, or preemption applies the configured cooldown.