quot;[{name}] no behaviour component for action '{a.id}'", this); _nextDecision = Time.time + Random.Range(0f, actionSet.decisionInterval); } void Update() { if (Time.time >= _nextDecision) { _nextDecision = Time.time + actionSet.decisionInterval; Decide(); } if (Running == null) return; var status = Running.Tick(Time.deltaTime); if (status != BehaviourStatus.Running) { Running.Exit(); Running = null; Reasoner.EndCurrent(Time.timeAsDouble); Decide(); // pick the next thing now rather than idling until the next interval } } void Decide() { var index = Reasoner.Decide(_board, Time.timeAsDouble); var next = index >= 0 && _behaviours.TryGetValue(actionSet.actions[index].id, out var b) ? b : null; if (next == Running) return; Running?.Exit(); Running = next; Running?.Enter(); } void OnDisable() { Running?.Exit(); Running = null; } } ``` - On `Awake` the brain collects every `IUtilityBehaviour` component on the GameObject by `ActionId` and warns about any action with no behaviour. Typos in ids are the most common setup mistake. - It decides every `decisionInterval` seconds, starting at a random offset so ten guards spawned together don't all think on the same frame. - Between decisions it ticks the running behaviour. When the behaviour returns `Done` or `Failed`, the brain ends the action (starting its cooldown) and decides again immediately. - Switching calls `Exit` on the old behaviour and `Enter` on the new one, so each behaviour sets up and cleans up its own `NavMeshAgent` state. ## 5.4 Stats and sensors **`GuardStats.cs`** ```csharp using UnityEngine; /// <summary>Minimal health and ammo so the example runs alone. Swap for your own health system.</summary> public sealed class GuardStats : MonoBehaviour { [SerializeField] float maxHealth = 100f; [SerializeField] int magazine = 12; public float Health { get; private set; } public int Ammo { get; private set; } public float Health01 => Health / maxHealth; public float Ammo01 => magazine == 0 ? 0f : (float)Ammo / magazine; public bool Dead => Health <= 0f; void Awake() { Health = maxHealth; Ammo = magazine; } public void Damage(float amount) => Health = Mathf.Max(0f, Health - amount); public void Heal(float amount) => Health = Mathf.Min(maxHealth, Health + amount); public bool TryUseAmmo() { if (Ammo <= 0) return false; Ammo--; return true; } public void Reload() => Ammo = magazine; } ``` **`GuardSensors.cs`** ```csharp using UnityEngine; /// <summary> /// Writes what the guard knows into its blackboard several times a second: own health and ammo, /// whether the player is visible, how far away they are, how long since last seen, and noises. /// Considerations only ever read these facts, never the scene, which keeps scoring cheap and testable. /// </summary> [RequireComponent(typeof(AIBlackboard))] public sealed class GuardSensors : MonoBehaviour { [SerializeField] Transform threat; // usually the player [SerializeField] float viewDistance = 20f; [SerializeField, Range(10f, 180f)] float viewAngle = 110f; [SerializeField] LayerMask occluders = ~0; [SerializeField] float sampleInterval = 0.1f; [SerializeField] float eyeHeight = 1.6f; public GuardStats Stats { get; private set; } public Vector3 LastKnownThreatPosition { get; private set; } public bool HasLastKnownPosition { get; private set; } AIBlackboard _board; float _lastSeen = float.NegativeInfinity; float _nextSample; Vector3 _noisePosition; float _noiseTime = float.NegativeInfinity; void Awake() { _board = GetComponent<AIBlackboard>(); Stats = GetComponent<GuardStats>(); } /// <summary>Call from gunshots, footsteps etc. within earshot.</summary> public void HearNoise(Vector3 position) { _noisePosition = position; _noiseTime = Time.time; if (!HasLastKnownPosition || Time.time - _lastSeen > 2f) { LastKnownThreatPosition = position; HasLastKnownPosition = true; } } void Update() { if (Time.time < _nextSample) return; _nextSample = Time.time + sampleInterval; if (Stats != null) { _board.Set("health", Stats.Health01); _board.Set("ammo", Stats.Ammo01); } var visible = false; if (threat != null) { var eye = transform.position + Vector3.up * eyeHeight; var target = threat.position + Vector3.up * 1f; var to = target - eye; var distance = to.magnitude; _board.Set("threat_distance", distance); if (distance <= viewDistance && Vector3.Angle(transform.forward, to) <= viewAngle * 0.5f) visible = !Physics.Raycast(eye, to / distance, out var hit, distance, occluders, QueryTriggerInteraction.Ignore) || hit.transform == threat || hit.transform.IsChildOf(threat); if (visible) { _lastSeen = Time.time; LastKnownThreatPosition = threat.position; HasLastKnownPosition = true; } } _board.Set("threat_visible", visible); _board.Set("seconds_since_seen", Mathf.Min(Time.time - _lastSeen, 999f)); _board.Set("seconds_since_noise", Mathf.Min(Time.time - _noiseTime, 999f)); _board.Set("has_lead", HasLastKnownPosition && !visible); } void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(transform.position, viewDistance); if (HasLastKnownPosition) { Gizmos.color = Color.red; Gizmos.DrawWireCube(LastKnownThreatPosition, Vector3.one * 0.5f); } } } ``` The sensors write these facts ten times a second: | Fact | Meaning | |---|---| | `health`, `ammo` | 0..1 from `GuardStats` | | `threat_distance` | metres to the player | | `threat_visible` | 1 if inside the view cone and not blocked by `occluders` | | `seconds_since_seen`, `seconds_since_noise` | capped at 999 | | `has_lead` | 1 if there's a last known position and the player isn't visible | Call `HearNoise(position)` from gunshots or footsteps to give the guard a lead it didn't see. For hearing, smell and memory that fade over time, see [[Organic Enemy Sensing]]. The line-of-sight raycast counts the player as visible if the ray hits nothing or hits the player. Put the player and the guard on layers excluded from **Occluders** if their own colliders could block the ray. ## 5.5 Six behaviours Each is a component that implements `IUtilityBehaviour` and drives the `NavMeshAgent`. **`PatrolBehaviour.cs`** ```csharp using UnityEngine; using UnityEngine.AI; /// <summary>Walks a loop of waypoints. Never finishes on its own; it's the low-priority default.</summary> public sealed class PatrolBehaviour : MonoBehaviour, IUtilityBehaviour { [SerializeField] Transform[] waypoints; [SerializeField] float speed = 1.8f; NavMeshAgent _agent; int _index; public string ActionId => "Patrol"; void Awake() => _agent = GetComponent<NavMeshAgent>(); public void Enter() { _agent.speed = speed; _agent.isStopped = false; if (waypoints.Length > 0) _agent.SetDestination(waypoints[_index].position); } public BehaviourStatus Tick(float dt) { if (waypoints.Length == 0) return BehaviourStatus.Failed; if (!_agent.pathPending && _agent.remainingDistance <= _agent.stoppingDistance + 0.1f) { _index = (_index + 1) % waypoints.Length; _agent.SetDestination(waypoints[_index].position); } return BehaviourStatus.Running; } public void Exit() { } } ``` **`AttackBehaviour.cs`** ```csharp using UnityEngine; using UnityEngine.AI; /// <summary>Closes to firing range, faces the target and fires on a timer. Fails when out of ammo.</summary> public sealed class AttackBehaviour : MonoBehaviour, IUtilityBehaviour { [SerializeField] Transform target; [SerializeField] float range = 12f; [SerializeField] float fireInterval = 0.6f; [SerializeField] float damage = 8f; [SerializeField] float speed = 3.5f; NavMeshAgent _agent; GuardStats _stats; float _cooldown; public string ActionId => "Attack"; void Awake() { _agent = GetComponent<NavMeshAgent>(); _stats = GetComponent<GuardStats>(); } public void Enter() { _agent.speed = speed; _agent.isStopped = false; } public BehaviourStatus Tick(float dt) { if (target == null) return BehaviourStatus.Failed; var distance = Vector3.Distance(transform.position, target.position); if (distance > range) { _agent.isStopped = false; _agent.SetDestination(target.position); return BehaviourStatus.Running; } _agent.isStopped = true; var flat = target.position - transform.position; flat.y = 0f; if (flat.sqrMagnitude > 0.001f) transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(flat), 360f * dt); _cooldown -= dt; if (_cooldown > 0f) return BehaviourStatus.Running; _cooldown = fireInterval; if (!_stats.TryUseAmmo()) return BehaviourStatus.Failed; if (target.TryGetComponent<GuardStats>(out var victim)) victim.Damage(damage); // placeholder hit; see the Weapons series return BehaviourStatus.Running; } public void Exit() => _agent.isStopped = false; } ``` The damage line is a placeholder that only works if the target has a `GuardStats`. Replace it with a hitscan shot from [[Weapons, Hitscan and Projectiles]] for a real game. **`ReloadBehaviour.cs`** ```csharp using UnityEngine; using UnityEngine.AI; /// <summary>Stands still for reloadSeconds, then refills the magazine and reports Done.</summary> public sealed class ReloadBehaviour : MonoBehaviour, IUtilityBehaviour { [SerializeField] float reloadSeconds = 1.8f; NavMeshAgent _agent; GuardStats _stats; float _left; public string ActionId => "Reload"; void Awake() { _agent = GetComponent<NavMeshAgent>(); _stats = GetComponent<GuardStats>(); } public void Enter() { _left = reloadSeconds; _agent.isStopped = true; } public BehaviourStatus Tick(float dt) { _left -= dt; if (_left > 0f) return BehaviourStatus.Running; _stats.Reload(); return BehaviourStatus.Done; } // Interrupted reloads don't refill: switching to Flee mid-reload costs the guard the reload. public void Exit() => _agent.isStopped = false; } ``` **`FleeBehaviour.cs`** ```csharp using UnityEngine; using UnityEngine.AI; /// <summary>Runs to the reachable point farthest from the threat among a few samples. Done on arrival.</summary> public sealed class FleeBehaviour : MonoBehaviour, IUtilityBehaviour { [SerializeField] Transform threat; [SerializeField] float fleeDistance = 15f; [SerializeField] float speed = 5f; [SerializeField] int samples = 8; NavMeshAgent _agent; public string ActionId => "Flee"; void Awake() => _agent = GetComponent<NavMeshAgent>(); public void Enter() { _agent.speed = speed; _agent.isStopped = false; var best = transform.position; var bestDistance = -1f; for (var i = 0; i < samples; i++) { var angle = i * Mathf.PI * 2f / samples; var candidate = transform.position + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * fleeDistance; if (!NavMesh.SamplePosition(candidate, out var hit, 3f, NavMesh.AllAreas)) continue; var d = threat != null ? Vector3.Distance(hit.position, threat.position) : 0f; if (d > bestDistance) { bestDistance = d; best = hit.position; } } _agent.SetDestination(best); } public BehaviourStatus Tick(float dt) => !_agent.pathPending && _agent.remainingDistance <= _agent.stoppingDistance + 0.2f ? BehaviourStatus.Done : BehaviourStatus.Running; public void Exit() { } } ``` **`HealBehaviour.cs`** ```csharp using UnityEngine; using UnityEngine.AI; /// <summary>Walks to the nearest heal station and regains health there. Done when full.</summary> public sealed class HealBehaviour : MonoBehaviour, IUtilityBehaviour { [SerializeField] Transform[] healStations; [SerializeField] float healPerSecond = 20f; [SerializeField] float speed = 3.5f; NavMeshAgent _agent; GuardStats _stats; Transform _station; public string ActionId => "Heal"; void Awake() { _agent = GetComponent<NavMeshAgent>(); _stats = GetComponent<GuardStats>(); } public void Enter() { _station = null; var best = float.MaxValue; foreach (var s in healStations) { var d = (s.position - transform.position).sqrMagnitude; if (d < best) { best = d; _station = s; } } _agent.speed = speed; _agent.isStopped = false; if (_station != null) _agent.SetDestination(_station.position); } public BehaviourStatus Tick(float dt) { if (_station == null) return BehaviourStatus.Failed; if (_agent.pathPending || _agent.remainingDistance > _agent.stoppingDistance + 0.3f) return BehaviourStatus.Running; _stats.Heal(healPerSecond * dt); return _stats.Health01 >= 0.999f ? BehaviourStatus.Done : BehaviourStatus.Running; } public void Exit() { } } ``` **`InvestigateBehaviour.cs`** ```csharp using UnityEngine; using UnityEngine.AI; /// <summary>Goes to the last known threat position (seen or heard), looks around, then reports Done.</summary> public sealed class InvestigateBehaviour : MonoBehaviour, IUtilityBehaviour { [SerializeField] float speed = 2.8f; [SerializeField] float lookAroundSeconds = 3f; NavMeshAgent _agent; GuardSensors _sensors; float _looking; public string ActionId => "Investigate"; void Awake() { _agent = GetComponent<NavMeshAgent>(); _sensors = GetComponent<GuardSensors>(); } public void Enter() { _looking = -1f; _agent.speed = speed; _agent.isStopped = false; if (_sensors.HasLastKnownPosition) _agent.SetDestination(_sensors.LastKnownThreatPosition); } public BehaviourStatus Tick(float dt) { if (!_sensors.HasLastKnownPosition) return BehaviourStatus.Failed; if (_looking < 0f) { if (_agent.pathPending || _agent.remainingDistance > _agent.stoppingDistance + 0.3f) return BehaviourStatus.Running; _looking = lookAroundSeconds; } transform.Rotate(0f, 90f * dt, 0f); _looking -= dt; return _looking > 0f ? BehaviourStatus.Running : BehaviourStatus.Done; } public void Exit() { } } ``` Notice that behaviours don't decide anything. Reload doesn't check whether a player is near; Flee doesn't check health. That's the reasoner's job. Behaviours only report when they're finished or can't continue. ## 5.6 The guard's action set Typing 15 considerations into the Inspector is slow and error-prone, so this Editor script builds the asset with the tuning from parts 2 and 3: **`CreateGuardActionSet.cs`** ```csharp #if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; /// <summary> /// Editor menu that creates the guard's action set from part 5 with every consideration filled in, /// so you start from working numbers instead of typing 15 curves into the Inspector. Put in Assets/Editor. /// </summary> public static class CreateGuardActionSet { [MenuItem("Tools/Utility AI/Create Guard Action Set")] static void Create() { var set = ScriptableObject.CreateInstance<UtilityActionSet>(); set.actions = Build(); var path = AssetDatabase.GenerateUniqueAssetPath("Assets/GuardActionSet.asset"); AssetDatabase.CreateAsset(set, path); AssetDatabase.SaveAssets(); Selection.activeObject = set; Debug.Log(quot;Created {path}"); } static Consideration C(string name, string input, ResponseCurve curve, float min = 0f, float max = 1f) => new Consideration { name = name, input = input, curve = curve, min = min, max = max }; public static List<UtilityAction> Build() => new List<UtilityAction> { new UtilityAction { id = "Attack", weight = 1f, commitSeconds = 1f, considerations = { C("Can see threat", "threat_visible", ResponseCurve.Step(0.5f)), C("Healthy enough", "health", ResponseCurve.Logistic(12f, 0.3f)), C("Has ammo", "ammo", ResponseCurve.Step(0.01f)), C("Close enough", "threat_distance", ResponseCurve.Linear(0.6f, 0.4f).Inverted(), 0f, 30f), } }, new UtilityAction { id = "Reload", weight = 1.2f, considerations = { C("Low ammo", "ammo", ResponseCurve.Polynomial(2f).Inverted()), C("Not too exposed", "threat_distance", ResponseCurve.Logistic(10f, 0.25f), 0f, 30f), } }, new UtilityAction { id = "Flee", weight = 1.5f, cooldownSeconds = 4f, commitSeconds = 2f, considerations = { C("Under threat", "threat_visible", ResponseCurve.Step(0.5f)), C("Badly hurt", "health", ResponseCurve.Polynomial(3f).Inverted()), } }, new UtilityAction { id = "Heal", weight = 1f, cooldownSeconds = 2f, considerations = { C("Hurt", "health", ResponseCurve.Linear().Inverted()), C("Threat not visible", "threat_visible", ResponseCurve.Step(0.5f).Inverted()), C("Not seen recently", "seconds_since_seen", ResponseCurve.Logistic(10f, 0.4f), 0f, 10f), } }, new UtilityAction { id = "Investigate", weight = 0.8f, cooldownSeconds = 6f, considerations = { C("Has a lead", "has_lead", ResponseCurve.Step(0.5f)), C("Lead is fresh", "seconds_since_seen", ResponseCurve.Linear().Inverted(), 0f, 20f), } }, new UtilityAction { id = "Patrol", weight = 0.25f, considerations = { C("Nothing going on", "threat_visible", ResponseCurve.Step(0.5f).Inverted()) } }, }; } #endif ``` Save it as `Assets/Editor/CreateGuardActionSet.cs` and run **Tools > Utility AI > Create Guard Action Set**. It creates `Assets/GuardActionSet.asset` and selects it. ## 5.7 Build the scene 1. Install **AI Navigation** 2.0.17 (**Window > Package Manager > + > Install package by name...**, `com.unity.ai.navigation`, version `2.0.17`). See [[NavMesh in Unity 6 (AI Navigation 2.x)]]. 2. Make a floor (**GameObject > 3D Object > Plane**, scale 5) and a few cubes as walls and cover. 3. Create an empty `NavMesh` GameObject, add **NavMesh Surface**, click **Bake**. 4. Make the player: a **Capsule** named `Player`. Give it any movement script (or move it by hand in the Scene view during Play mode) and add **Guard Stats** so the placeholder attack has something to damage. 5. Make the guard: another **Capsule** named `Guard`. Add **Nav Mesh Agent**, **AI Blackboard**, **Guard Stats**, **Guard Sensors** (drag `Player` into **Threat**), **Utility Brain** (drag `GuardActionSet` into **Action Set**), and the six behaviours: **Patrol**, **Attack**, **Reload**, **Flee**, **Heal** and **Investigate Behaviour**. Drag `Player` into Attack's **Target** and Flee's **Threat**. 6. Create three or four empty GameObjects as patrol waypoints and drag them into Patrol's **Waypoints**. Create one or two heal stations (a green cylinder works) and drag them into Heal's **Heal Stations**. 7. Add **Utility Debug View** to the guard (part 6) and enable **Gizmos** in the Scene view. 8. Press Play. The guard patrols. Walk the player into its view: it attacks. Lower its health in the Inspector (**Guard Stats** has no public field for current health, so use the Debug Inspector or call `Damage` from a test button): it flees, then heals once out of sight. *(Untested in Play mode: the behaviours have only been compiled. Expect to adjust `viewAngle`, ranges and speeds for your level.)* Next: [[6. Debugging Tuning Tests and Pitfalls]].