Table of Contents

Class AIController

Namespace
FishMMO.Server.Implementation.World.SceneServer.AI
Assembly
FishMMO.Server.dll

Controls AI navigation, state transitions, and behavior for NPCs using NavMeshAgent. Handles movement, enemy detection, leash logic, waypoints, state management, and provides a virtual camera for aiming abilities at targets during combat.

[RequireComponent(typeof(NavMeshAgent))]
[DisallowMultipleComponent]
public class AIController : MonoBehaviour, IAIController, IAINavigation, IAIStateMachine, IAIWaypoints, INPCBrain, ICharacterBehaviour
Inheritance
Object
Component
Behaviour
MonoBehaviour
AIController
Implements
Inherited Members
MonoBehaviour.IsInvoking()
MonoBehaviour.CancelInvoke()
MonoBehaviour.StopCoroutine(Coroutine)
MonoBehaviour.StopAllCoroutines()
MonoBehaviour.destroyCancellationToken
MonoBehaviour.useGUILayout
MonoBehaviour.didStart
MonoBehaviour.didAwake
MonoBehaviour.runInEditMode
Behaviour.enabled
Behaviour.isActiveAndEnabled
Component.GetComponent<T>()
Component.TryGetComponent<T>(out T)
Component.GetComponentInChildren<T>()
Component.GetComponentsInChildren<T>()
Component.GetComponentInParent<T>()
Component.GetComponentsInParent<T>()
Component.GetComponents<T>()
Component.GetComponentIndex()
Component.CompareTag(TagHandle)
Component.transform
Component.transformHandle
Component.gameObject
Component.tag
Object.GetEntityId()
Object.MemberwiseClone()
Object.GetInstanceID()
Object.GetHashCode()
Object.InstantiateAsync<T>(T)
Object.InstantiateAsync<T>(T, Transform)
Object.InstantiateAsync<T>(T, Vector3, Quaternion)
Object.InstantiateAsync<T>(T, Transform, Vector3, Quaternion)
Object.Instantiate(Object, Vector3, Quaternion)
Object.Instantiate(Object, Vector3, Quaternion, Transform)
Object.Instantiate(Object)
Object.Instantiate(Object, Scene)
Object.Instantiate<T>(T, InstantiateParameters)
Object.Instantiate<T>(T, Vector3, Quaternion, InstantiateParameters)
Object.Instantiate(Object, Transform)
Object.Instantiate<T>(T)
Object.Instantiate<T>(T, Vector3, Quaternion)
Object.Instantiate<T>(T, Vector3, Quaternion, Transform)
Object.Instantiate<T>(T, Transform)
Object.Destroy(Object)
Object.DestroyImmediate(Object)
Object.DontDestroyOnLoad(Object)
Object.DestroyObject(Object)
Object.FindObjectsOfType<T>()
Object.FindObjectsByType<T>(FindObjectsSortMode)
Object.FindObjectsByType<T>(FindObjectsInactive, FindObjectsSortMode)
Object.FindObjectOfType<T>()
Object.FindFirstObjectByType<T>()
Object.FindAnyObjectByType<T>()
Object.FindFirstObjectByType<T>(FindObjectsInactive)
Object.FindAnyObjectByType<T>(FindObjectsInactive)
Object.FindObjectsByType<T>()
Object.FindObjectsByType<T>(FindObjectsInactive)
Object.ToString()
Object.name
Object.hideFlags

Remarks

Server only, and never on a prefab. AIBrainHost adds this component (and, through UnityEngine.RequireComponent, its UnityEngine.AI.NavMeshAgent) the first time the server spawns an NPC, keeps it across pool reuse, and drives it from one network-tick subscription for every brain. A client never compiles this type, so an NPC prefab carries no AI component and no AI data.

A plain UnityEngine.MonoBehaviour, not a NetworkBehaviour: FishNet indexes a NetworkObject's behaviours at edit time and cannot take one added at runtime. It registers with its character like any CharacterBehaviour, so character.TryGet(out IAIController) and TryGet(out INPCBrain) resolve it.

Fields

ARRIVAL_TOLERANCE

Distance from the destination at which an NPC counts as arrived, in world units.

public const float ARRIVAL_TOLERANCE = 1

Field Value

float

AiTickRate

How many times per second this NPC's brain runs, in hertz.

[Header("Tick Rate")]
[Tooltip("Brain updates per second. 5-10 is the useful band. Rounded to a divisor of the network tick rate.")]
[Range(1, 30)]
public float AiTickRate

Field Value

float

Remarks

Rounded to the nearest whole divisor of the FishNet tick rate, so the brain always lands on network ticks and never drifts against them. At the project's 30 Hz network tick, 8 Hz resolves to every 4th tick — 7.5 Hz exactly, forever, on any hardware. EffectiveAiTickRate reports what a requested rate actually resolved to.

5-10 Hz is the useful band for an MMO brain. Decisions below about 5 Hz start to read as sluggish reaction time to a player; above about 10 Hz the NPC is re-deciding faster than its own pathing and animation can respond, so the extra ticks buy nothing but CPU.

AllyScanTimer

Seconds until a healer archetype rescans for wounded allies.

[NonSerialized]
public float AllyScanTimer

Field Value

float

AttackCooldownTimer

Seconds remaining before this NPC may activate another ability.

[NonSerialized]
public float AttackCooldownTimer

Field Value

float

Remarks

Lives on the controller, not on the attacking state, because the state is a ScriptableObject shared by every NPC of that archetype — a timer stored there would be one global pacing clock for the whole population.

CachedHealTarget

The ally a healer archetype last chose to heal, re-validated cheaply between scans.

[NonSerialized]
public ICharacter CachedHealTarget

Field Value

ICharacter

ClimbAreaName

The name of the NavMesh area the climbables' links are in (SceneNavMeshes).

public const string ClimbAreaName = "Climb"

Field Value

string

ClimbLinkMatchMetres

How far a link's end may be from a climbable's foot or landing and still be that climbable's link, metres.

public const float ClimbLinkMatchMetres = 1.5

Field Value

float

DEFAULT_AI_TICK_RATE

The brain rate every NPC runs unless its AiTickRate is changed, and the rate AIBrainHost ticks packs at.

public const float DEFAULT_AI_TICK_RATE = 8

Field Value

float

DeepWaterAreaName

The name of the NavMesh area the bake gives water too deep to wade (SceneNavMeshBaker).

public const string DeepWaterAreaName = "Deep Water"

Field Value

string

FACING_TOLERANCE_DEGREES

Angle, in degrees, within which the NPC counts as already facing its look target. Well under what the rotation compression on the wire can show.

public const float FACING_TOLERANCE_DEGREES = 0.1

Field Value

float

FlankTimer

Seconds of manoeuvring budget remaining for RogueAttackingState's flanking attempt. Per-NPC for the same reason as AttackCooldownTimer.

[NonSerialized]
public float FlankTimer

Field Value

float

HEADING_SPEED_THRESHOLD

Speed below which the agent's velocity is not worth turning toward, in metres per second.

public const float HEADING_SPEED_THRESHOLD = 0.05

Field Value

float

Kite

Per-NPC kiting allowance. See AIKiteBudget.

[NonSerialized]
public AIKiteBudget Kite

Field Value

AIKiteBudget

KnockbackDeceleration

How quickly a knockback bleeds off, metres per second per second. An 8 m/s shove slides about 1.3 m over a third of a second.

[Tooltip("How quickly a knockback bleeds off, m/s per second. 8 m/s at 24 slides ~1.3 m over ~0.33 s.")]
public float KnockbackDeceleration

Field Value

float

LavaAreaName

The name of the NavMesh area the bake gives molten lava (swimmable only by the fire-immune).

public const string LavaAreaName = "Lava"

Field Value

string

LookTarget

The current look target for the AI (used for facing/rotation).

public Transform LookTarget

Field Value

Transform

MAX_KNOCKBACK_SPEED

The fastest a knockback may push, metres per second, however many land at once.

public const float MAX_KNOCKBACK_SPEED = 20

Field Value

float

OFF_MESH_RESEAT_INTERVAL

Seconds between attempts to put an agent that has left the NavMesh back on it.

public const float OFF_MESH_RESEAT_INTERVAL = 1

Field Value

float

OrbitAngle

Per-NPC orbit angle (radians) used by OrbitState. Stored here instead of on the ScriptableObject to avoid the shared-instance mutable state problem.

[NonSerialized]
public float OrbitAngle

Field Value

float

PetStuckTimer

Seconds a pet has spent unable to reach its owner. Drives the follow state's teleport escape hatch. Per-NPC, for the same reason as the other timers here.

[NonSerialized]
public float PetStuckTimer

Field Value

float

PetSupportAllies

The friends a pet's last support scan found near it, besides its owner and itself. Re-validated on every use; refilled when PetSupportScanTimer runs out.

[NonSerialized]
public readonly List<ICharacter> PetSupportAllies

Field Value

List<ICharacter>

PetSupportScanTimer

Seconds until a pet rescans for friends to heal or buff. See PetSupport.

[NonSerialized]
public float PetSupportScanTimer

Field Value

float

RandomizeState

If true, the AI will randomize its movement state.

public bool RandomizeState

Field Value

bool

RepathInterval

[Header("Pathfinding")]
[Tooltip("Minimum seconds between NavMeshAgent.SetDestination calls via SetThrottledDestination.")]
public float RepathInterval

Field Value

float

Retreat

Per-NPC retreat memory: how long it has run, how often, and whether it may run again. See AIRetreatBudget.

[NonSerialized]
public AIRetreatBudget Retreat

Field Value

AIRetreatBudget

Remarks

Lives here, on the instance, and not on the retreat state asset. That asset is shared by every NPC that flees, so a counter stored on it would be one counter for the whole server — and it holds authored configuration, which runtime bookkeeping has no business being written into. Non-serialized for the same reason: this is state, not prefab data.

RotationIndex

Per-NPC rotation index used by AIAbilityRotation in Sequence mode. Tracks which entry in the rotation to try next.

[NonSerialized]
public int RotationIndex

Field Value

int

STUCK_SPEED_THRESHOLD

Speed below which an agent that is supposed to be moving counts as not moving.

public const float STUCK_SPEED_THRESHOLD = 0.05

Field Value

float

SeparationRadius

[Header("Separation")]
[Tooltip("Distance at which another NPC starts pushing this one away. 0 = twice the agent radius.")]
public float SeparationRadius

Field Value

float

SeparationSpeed

Push speed when fully overlapped with another NPC, in metres per second.

[Tooltip("Push speed when fully overlapped with another NPC. 0 disables separation.")]
public float SeparationSpeed

Field Value

float

ShoreWaitTimer

Seconds this NPC has waited at the water's edge for a target out in it.

public float ShoreWaitTimer

Field Value

float

StuckTimeout

Seconds of no progress before the NPC is considered stuck.

[Header("Navigation Recovery")]
[Tooltip("Seconds of no movement, while trying to move, before the NPC is considered stuck.")]
public float StuckTimeout

Field Value

float

StuckWarpTimeout

Seconds of continued no progress after the first recovery attempt before the NPC is teleported to its destination. 0 disables teleport recovery.

[Tooltip("Seconds stuck before the NPC is warped free. 0 = never warp.")]
public float StuckWarpTimeout

Field Value

float

SubStateTimer

Countdown used by bounded combat sub-states such as OrbitState to know when their manoeuvre is finished. Per-NPC, for the same reason as the other timers here.

[NonSerialized]
public float SubStateTimer

Field Value

float

SupportTarget

The friend this NPC is currently healing or buffing, or on its way to: while set, the aim (UpdateAim(float)) points at it instead of at Target.

[NonSerialized]
public ICharacter SupportTarget

Field Value

ICharacter

Remarks

The aim used to follow Target alone, and Target means "the thing I am fighting" everywhere in the AI. A support cast that launches along the aim — a healing mote, which spawns with the aim rotation — therefore flew at the enemy however far the body had turned toward the ally, and a heal that spares enemies healed nobody.

Set by whoever starts the support (PetSupport, HealerAttackingState) and held for the length of the cast, then cleared by EndSupportAim(AIController) on the first tick nothing is being cast.

SweepHits

Buffer for storing colliders hit during enemy sweep. Grown on demand — see SweepForEnemies(AIController, List<ICharacter>).

public Collider[] SweepHits

Field Value

Collider[]

Remarks

Not a fixed 20. A non-allocating overlap returns at most buffer.Length results and says nothing about how many it discarded, and the ones it discarded were chosen by the physics broadphase — so an NPC in a fight larger than its buffer detected an arbitrary, run-varying subset of its attackers and ignored the rest. The sweep re-queries into a larger buffer through TargetOrdering.TryGrowQueryBuffer until it stops coming back full, which is the same treatment every other spatial query in the project gets.

TurnRate

How quickly the NPC turns to face its look target, in radians-ish per second.

[Header("Facing")]
[Tooltip("How quickly the NPC turns to face its target. Higher is snappier.")]
public float TurnRate

Field Value

float

Remarks

Feeds an exponential smoothing factor, so the value is a rate rather than a hard angular speed: higher snaps faster, and the result is identical at any frame rate.

UnreachableTargetTimer

Seconds the NPC has spent unable to reach its combat target.

[NonSerialized]
public float UnreachableTargetTimer

Field Value

float

WasAttackingLastTick

True when the previous combat tick resolved to attacking or holding position rather than moving. Feeds the range hysteresis in AICombatDecision.

[NonSerialized]
public bool WasAttackingLastTick

Field Value

bool

Waypoints

The waypoints available to this AI controller.

public Vector3[] Waypoints

Field Value

Vector3[]

Properties

AbilityRotation

Optional ability rotation. When assigned, PickBestAbility(float) evaluates the rotation first. If no entry matches and FallbackToDefault is true, the default scoring-based picker runs as a fallback. A boss phase's override wins over the archetype's while the phase is in force.

public AIAbilityRotation AbilityRotation { get; }

Property Value

AIAbilityRotation

Agent

The NavMeshAgent component used for navigation.

public NavMeshAgent Agent { get; }

Property Value

NavMeshAgent

Aggression

Convenience accessor for the underlying aggression controller.

public AggressionController Aggression { get; }

Property Value

AggressionController

AggressionState

The aggression (threat) state for this NPC. Manages the threat table, event subscriptions, and target re-evaluation timer. One instance per NPC — not shared.

public AggressionState AggressionState { get; }

Property Value

AggressionState

AiTickIndex

Monotonic count of brain updates. Drives the LOD stagger.

public uint AiTickIndex { get; }

Property Value

uint

AimLeadSpeed

Travel speed of the ability being cast, or 0 when nothing is being cast or the ability has no travel time.

public float AimLeadSpeed { get; }

Property Value

float

Remarks

Set by RollAimForCast(AIAimProfile, float) from the ability it is about to cast, and read on every network tick by UpdateAim(float) to derive a lead time from the current distance.

Why the speed is held rather than the lead time. The flight time is distance over speed, and the distance changes: the bolt does not leave the caster's hand until the windup finishes — 0.4 s on Orc Firebolt — and the target keeps moving throughout. Baking the lead seconds at the moment the cast was queued would aim the shot at where the target was going to be a windup ago. Keeping the speed and recomputing the time each tick means the lead is correct at the instant the projectile actually spawns, and it costs one subtraction and a divide on a tick that already solves a look rotation.

AimLock

Seconds the current target has been continuously tracked, which drives the aim accuracy ramp.

public float AimLock { get; }

Property Value

float

Remarks

Reset whenever Target changes, so a target re-acquired after a disengage must be re-acquired by the aim as well. Advanced only while the controller is in a tier that runs combat — see UpdateAim(float) — because a ramp that measured wall-clock time with a target rather than time actually spent tracking one would hand an NPC full accuracy the moment a player walked back into range.

AimOrigin

The world-space point this NPC's abilities fire from.

public Vector3 AimOrigin { get; }

Property Value

Vector3

Remarks

Computed, never cached. This returns exactly what Resolve(ICharacter) returns on every peer, and it must: only the aim direction is replicated, so wherever a shot is actually spawned the origin is re-derived independently. A cached copy of a derived value is the defect this replaces — the old code solved its aim direction from the character root while the projectile left from root + 1.45 m, and nothing could detect the disagreement.

One point, two consumers. The aim direction is solved from here and HasLineOfSight(AIController, ICharacter) rays from here, so the point an NPC shoots from and the point it sees from are the same by construction. They used to differ — vision rayed from the ankles, aim was solved from the ankles, the bolt left the eye — and that 1.45 m of parallel-ray displacement is what made every fireball pass over its target's head, at any range.

AimRotation

The rotation whose forward vector is the direction this NPC aims.

public Quaternion AimRotation { get; }

Property Value

Quaternion

Remarks

Written by UpdateAim(float) on every network tick, because AbilityController.PopulateAiAim reads it on every network tick. It is held as state rather than derived on demand because the per-cast scatter offset is deliberately fixed for the duration of a cast — see AimScatter — so the result depends on more than the current positions.

AimScatter

The angular error held for the current cast.

public Quaternion AimScatter { get; }

Property Value

Quaternion

Remarks

Rolled once when a cast begins, by BaseAttackingState.ActivateAbility, and held until the next cast. Held rather than re-rolled per tick on purpose — see RollScatter(float, float, float) — so an inaccurate NPC tracks its target with a stable bias instead of spraying around it.

Archetype

The archetype this NPC runs. See the field remarks for what assigning one at runtime does.

public AIArchetypeTemplate Archetype { get; set; }

Property Value

AIArchetypeTemplate

AttackingState

The combat state, or null when this NPC cannot fight. A boss phase's override wins over the archetype's while the phase is in force.

public BaseAIState AttackingState { get; }

Property Value

BaseAIState

AvoidancePriority

The NavMeshAgent avoidance priority (affects how strongly it avoids other agents).

public AgentAvoidancePriority AvoidancePriority { get; }

Property Value

AgentAvoidancePriority

BehaviorTree

Optional behavior tree that provides high-level decision making above the state machine. When assigned, the tree is evaluated each tick before the current state's UpdateState. If the tree produces a state transition (returns Success), UpdateState is skipped that tick. A boss phase's override wins over the archetype's while the phase is in force.

public AIBehaviorTree BehaviorTree { get; }

Property Value

AIBehaviorTree

BossScript

The boss script this NPC runs, or null. Assigning one starts it from its first phase.

public BossScript BossScript { get; set; }

Property Value

BossScript

Remarks

Assigned by AIBrainHost from the NPC prefab's catalogue entry on every spawn, so the runtime state is rebuilt here rather than once at initialisation.

BossState

Runtime state for the boss script. Null when no BossScript is assigned.

public BossScriptState BossState { get; }

Property Value

BossScriptState

CanClimb

Whether this NPC climbs: its archetype says so (on by default, as is an NPC with no archetype).

public bool CanClimb { get; }

Property Value

bool

Character

The character this brain drives.

public ICharacter Character { get; }

Property Value

ICharacter

ClimbArea

The climb NavMesh area's index; -1 when the project has none.

public static int ClimbArea { get; }

Property Value

int

CombatTargetBuffer

Reusable buffer for collecting targets during combat state updates. Used by attacking states to avoid per-frame GC allocations.

public List<ICharacter> CombatTargetBuffer { get; }

Property Value

List<ICharacter>

CurrentLodTier

Current AI LOD tier. Determines how frequently this NPC's brain ticks.

public AILodTier CurrentLodTier { get; }

Property Value

AILodTier

CurrentState

The current AI state.

public BaseAIState CurrentState { get; }

Property Value

BaseAIState

CurrentWaypointIndex

The current waypoint index.

public int CurrentWaypointIndex { get; }

Property Value

int

DeadState

Optional state entered on death.

public BaseAIState DeadState { get; }

Property Value

BaseAIState

DeepWaterArea

The deep-water NavMesh area's index; -1 when the project has none.

public static int DeepWaterArea { get; }

Property Value

int

EffectiveAiTickRate

The brain rate actually achieved, after rounding to a whole number of network ticks.

public float EffectiveAiTickRate { get; }

Property Value

float

EnemySweepRate

How often (in seconds) to sweep for nearby enemies while out of combat.

public float EnemySweepRate { get; }

Property Value

float

Group

The pack this NPC fights with, or null. Written only by NPCGroup.

public NPCGroup Group { get; }

Property Value

NPCGroup

Remarks

Set when a pack spawner spawns the NPC (SpawnerRuntime.JoinPack) or a boss calls it in as an add, and cleared when it leaves: on death (SuspendForCorpse()), on despawn and pool reset (FishMMO.Server.Implementation.World.SceneServer.AI.AIController.ResetForPool()), and on destruction.

GroupRole

This NPC's role within its pack; None outside one. Written only by NPCGroup.

public NPCGroupRole GroupRole { get; }

Property Value

NPCGroupRole

HasNearbyPlayer

True when a player is close enough for this NPC's expensive per-tick polling — the enemy sweep above all — to be worth doing.

public bool HasNearbyPlayer { get; }

Property Value

bool

Remarks

Inside the Nearby band, or unmeasured. Never false merely because nothing is streaming this NPC: an Observers.Count < 1 test here meant a budget-evicted monster could not aggro anybody, including the player who had just pulled it.

HasPackSlot

True while the pack's tactic has a slot for this NPC: it is fighting the pack's focus and the pack has a tactic.

public bool HasPackSlot { get; }

Property Value

bool

Home

The anchor this AI leashes and wanders around.

public Vector3 Home { get; set; }

Property Value

Vector3

Remarks

For a normal NPC this is its spawn point. For a pet it is its owner — a pet's home is a moving target, and every leash check, wander radius and return-home destination in the AI reads this property, so anchoring it to the owner here fixes all of them at once. Previously each site that cared had to remember to overwrite the field with the owner's position, and the ones that forgot dragged the pet back toward wherever it happened to be summoned.

A pet ordered to Stay is the exception: it holds the position it was standing in, which is what the setter stores.

IdentityKey

A well-mixed hash of this pooled instance's identity: the one source every per-NPC phase, stagger and tie-break is drawn from.

public uint IdentityKey { get; }

Property Value

uint

Remarks

Hashed rather than used raw. Unity hands out instance IDs sequentially across every object and component an instantiation creates, so a camp of one prefab spawned together tends to have IDs a constant stride apart — and a stride that shares a factor with the brain interval puts the whole camp on a fraction of the brain ticks, id % 4 on the same one at worst. The hash is a bijection on 32 bits, so distinct instances still get distinct keys, which is what lets AISeparation break a tie with it.

Stable for the life of the pooled object, so an NPC keeps its phases across respawns and nothing draws from its seeded RNG to pick them.

IdleState

The state this NPC falls back to when it has nothing to do.

public BaseAIState IdleState { get; }

Property Value

BaseAIState

InDeepWater

Whether the NPC stands on deep water now (the NavMesh's Deep Water area).

public bool InDeepWater { get; }

Property Value

bool

InitialState

The state the NPC starts in when it spawns.

public BaseAIState InitialState { get; }

Property Value

BaseAIState

Initialized

True once InitializeOnce(ICharacter) has bound this brain to its character.

public bool Initialized { get; }

Property Value

bool

An NPC on a climbable's link now (on the way to it, on it, or over its top).

public bool IsClimbingLink { get; }

Property Value

bool

IsEvading

True while the NPC is walking home after a leash pulled it out of a fight. An evading NPC takes no damage, no threat, no taunt, no debuff from another character and no knockback, and a hit on it is reported to the attacker as Evade. Shared code asks through CharacterEvade.RefusesHostileEffects, not here directly.

public bool IsEvading { get; }

Property Value

bool

Remarks

The evade is what stops a leash being farmed: without it a player could drag a mob to the edge of its leash and hit it all the way home, or hit it once on the way to reset the fight on their own terms. Server-side only — a client has no brain, so this is never true there.

Separate from Immortal on purpose. Immortal is authored on the prefab (a training dummy, a quest giver), set on corpses and toggled by administrators; the brain borrowing it for an evade would have to save and restore it around every way out of the return, and one missed path would leave a mob unkillable for the rest of its life. The evade is derived from the brain's current state instead, so it ends whenever the return does, however it ends.

IsHandingOverFight

True only while FishMMO.Server.Implementation.World.SceneServer.AI.AIController.HandOverFight() is moving an ongoing fight from one attacking state to another. Exit(AIController) reads it, alongside PendingState, to tell a hand-over from a disengage.

public bool IsHandingOverFight { get; }

Property Value

bool

IsInCombatState

True while the current state is part of a fight: the attacking state itself, or a combat sub-state (orbit, flank, strafe, retreat) that keeps the combat target.

public bool IsInCombatState { get; }

Property Value

bool

Remarks

Not CurrentState == AttackingState. A hit taken mid-orbit or mid-retreat is part of the fight already in progress; reading only the attacking state would let every such hit yank the NPC back into it and onto whoever hit it last, which would end every flee the moment the pursuer landed a blow.

IsKnockedBack

True while a knockback is still moving this NPC.

public bool IsKnockedBack { get; }

Property Value

bool

IsRunning

True while the brain is live: prepared for this spawn, not suspended for a corpse, and not quarantined by the host.

public bool IsRunning { get; }

Property Value

bool

LandAreas

Every NavMesh area but deep water and lava: where an NPC that can swim in neither may go.

public static int LandAreas { get; }

Property Value

int

LastAiDeltaTime

Seconds elapsed during the AI tick currently executing.

public float LastAiDeltaTime { get; }

Property Value

float

Remarks

Published so helpers reached from deep inside a state's update — which do not receive deltaTime as a parameter — can still advance per-tick timers on the same clock the state machine runs on, rather than sampling UnityEngine.Time.deltaTime and getting one frame instead of one AI tick.

LastPathWasPartial

True when the last accepted destination request produced only a partial path.

public bool LastPathWasPartial { get; }

Property Value

bool

Remarks

Consumed by GetMovementProgress(float, float): an agent that has run out of a partial path has stopped somewhere it was not asked to go, which is a stuck condition rather than an arrival.

LavaArea

The lava NavMesh area's index; -1 when the project has none.

public static int LavaArea { get; }

Property Value

int

LodSettings

Optional LOD settings for distance-based update throttling. When assigned, the brain runs distance-based tiers by nearest player: Active, Nearby, Far, and Dormant (nobody within the Far band). Null means always Active: every AI tick runs the full pipeline.

public AILodSettings LodSettings { get; }

Property Value

AILodSettings

MaxOffensiveReach

The longest reach among this NPC's offensive abilities, in metres. 0 when it knows none.

public float MaxOffensiveReach { get; }

Property Value

float

Remarks

What an archetype's spacing is checked against: a comfort distance no ability can attack from is not kiting, it is running away. Refreshed with the ability cache.

NetworkManager

The network manager the character is spawned under, or null.

public NetworkManager NetworkManager { get; }

Property Value

NetworkManager

NetworkObject

The character's network object, or null before the brain is bound.

public NetworkObject NetworkObject { get; }

Property Value

NetworkObject

NpcBreathSeconds

Seconds of breath this NPC has left (divers); its archetype's full breath when it has not been under.

public float NpcBreathSeconds { get; }

Property Value

float

NpcRNG

The seeded RNG from the owning NPC. All AI randomisation should use this instead of DeterministicRNG.Shared so that NPC behaviour is fully deterministic given the same seed. Returns null for non-NPC characters.

public DeterministicRNG NpcRNG { get; }

Property Value

DeterministicRNG

OwningPet

The pet this controller drives, or null when it drives a normal NPC.

public Pet OwningPet { get; }

Property Value

Pet

PackSlotAngle

The bearing around the pack's focus this NPC's tactic assigned it, in radians, in the OrbitState convention. Meaningful only while HasPackSlot.

public float PackSlotAngle { get; }

Property Value

float

PatrolState

Waypoint movement, or null when the archetype does not patrol.

public BaseAIState PatrolState { get; }

Property Value

BaseAIState

PendingState

The state that is about to become CurrentState, visible to the outgoing state's Exit(AIController).

public BaseAIState PendingState { get; }

Property Value

BaseAIState

Remarks

Exists so an attacking state can tell "combat is over" from "combat is continuing in a sub-state". Exit(AIController) clears the target and interrupts the cast, which is right when the NPC disengages and catastrophic when it does not: the melee archetype's flanking roll called ChangeState(GetBehindState), Exit wiped the target on the way out, and GetBehindState then found no target and dropped the NPC to idle. Every configured orbit / flank / strafe roll silently ended the fight.

Null outside of a transition.

Personality

Optional combat personality that biases ability selection via per-category score multipliers. When assigned, PickBestAbility(float) applies the personality's weight and bonus to each ability's score. Two NPCs with the same abilities but different personalities will favour different abilities in combat.

public AICombatPersonality Personality { get; }

Property Value

AICombatPersonality

PhysicsScene

The physics scene associated with this AI controller.

public PhysicsScene PhysicsScene { get; }

Property Value

PhysicsScene

Prepared

True between the host preparing this brain for a spawn and the NPC leaving the world.

public bool Prepared { get; }

Property Value

bool

Remarks

Owned by AIBrainHost. A spawner prepares the brain before the network spawn so the agent is warped onto the mesh first; the host's spawn hook prepares any NPC nothing else did.

Quarantined

True once the host has stopped ticking this brain because it kept throwing. Cleared when the NPC is next prepared. See MaxConsecutiveTickFaults.

public bool Quarantined { get; }

Property Value

bool

RequestedDestination

The destination most recently requested through TryMoveTo(Vector3, bool, float).

public Vector3 RequestedDestination { get; }

Property Value

Vector3

RetreatState

Flee state, or null when the archetype fights to the death.

public BaseAIState RetreatState { get; }

Property Value

BaseAIState

ReturnHomeState

Leash return, or null when the archetype never leashes.

public BaseAIState ReturnHomeState { get; }

Property Value

BaseAIState

RunSpeed

Metres per second at a run (fleeing, hunting, charging): the species' own for wildlife, else the shared NPC run.

public float RunSpeed { get; }

Property Value

float

ServerManager

The server manager of NetworkManager, or null.

public ServerManager ServerManager { get; }

Property Value

ServerManager

Shelter

Whether and how this NPC shelters from the weather, or null when the archetype says nothing about it. Off unless an archetype turns it on (Q15).

public AIShelterSettings Shelter { get; }

Property Value

AIShelterSettings

StateDeltaTime

Seconds covered by the state update currently executing.

public float StateDeltaTime { get; }

Property Value

float

Remarks

A state updates every updateRate seconds, not every brain tick, so a timer a state advances must use this rather than LastAiDeltaTime. See AIStateClock for what happened when it did not.

Swim

Whether and how this NPC swims, or null when the archetype says nothing (it does not).

public AISwimSettings Swim { get; }

Property Value

AISwimSettings

Target

The current target for the AI (e.g., enemy, destination).

public Transform Target { get; set; }

Property Value

Transform

TargetCharacter

The current combat target as an ICharacter, or null.

public ICharacter TargetCharacter { get; }

Property Value

ICharacter

Remarks

Prefer this over calling Target.GetComponent<ICharacter>(). The result is cached against the transform, so it costs a field read rather than an interface component lookup. Returns null when the pooled object behind the transform has been re-issued to a different character since targeting — see FishMMO.Server.Implementation.World.SceneServer.AI.AIController.cachedTargetCharacterID — so every consumer's null check drops the stale target instead of attacking the pool's next occupant.

TargetClosingSpeed

How fast the current target is closing on this NPC, in units per second.

public float TargetClosingSpeed { get; }

Property Value

float

Remarks

Negative when the target is moving away, zero with no target. What tells a retreating NPC the difference between "I have escaped" and "it is still coming" — the distinction the reported behaviour was missing. Measured from the sampled TargetVelocity rather than from a change in distance, so it is available on the same tick the target moves instead of a tick later, and it does not confuse a target circling at a steady radius for one closing in.

TargetReevaluationTimer

Per-NPC timer for mid-combat target re-evaluation. Delegates to TargetReevaluationTimer.

public float TargetReevaluationTimer { get; set; }

Property Value

float

TargetVelocity

The current target's estimated velocity in units per second.

public Vector3 TargetVelocity { get; }

Property Value

Vector3

Remarks

Sampled rather than asked for. Nothing in the AI currently tracks target motion, and the alternative — reading the target's own velocity — would mean a different source per character type: a player's motion lives on the KCC motor, an NPC's on its agent, and a pet's on whichever of the two it is. The aim needs one number in one unit for every kind of target, and differencing the replicated position gives exactly that with no new dependency.

TimeManager

The time manager of NetworkManager, or null.

public TimeManager TimeManager { get; }

Property Value

TimeManager

WalkSpeed

Metres per second at a walk: the species' own for wildlife, else the shared NPC walk.

public float WalkSpeed { get; }

Property Value

float

WanderState

Random movement around the home position, or null when the archetype does not wander.

public BaseAIState WanderState { get; }

Property Value

BaseAIState

WaterVerdict

What the last chase across water came to.

public WaterVerdict WaterVerdict { get; }

Property Value

WaterVerdict

Methods

AgentIsUsable()

True when the NavMeshAgent can accept movement commands.

public bool AgentIsUsable()

Returns

bool

True if the agent is enabled and on a NavMesh.

Remarks

Unity rejects isStopped and SetDestination with an error for an agent that is disabled or not on a NavMesh. Spawn paths legitimately touch the brain around the moment an object is activated and placed, so guard rather than log a wall of errors.

AllowsLeashReset(AILodTier, bool, bool, float, float)

Whether a tier change may run the leash reset — interrupt, full heal, threat clear, boss phase reset — as a pure function so it is testable without a NetworkManager.

public static bool AllowsLeashReset(AILodTier newTier, bool inAttackingState, bool hasProximityMeasurement, float nearestPlayerSqrDistance, float leashResetSqrDistance)

Parameters

newTier AILodTier

Tier being transitioned to.

inAttackingState bool

True when the NPC is currently in a BaseAttackingState.

hasProximityMeasurement bool

False when nothing has measured the nearest player yet.

nearestPlayerSqrDistance float

Squared distance to the nearest player.

leashResetSqrDistance float

Squared distance a player must be beyond for the reset to be allowed.

Returns

bool

True when the reset may run.

Remarks

The reset is authoritative simulation state, so it asks proximity directly rather than trusting the tier that triggered it. The tier says how much WORK to do; only distance says whether a fight is really over.

Truth table, first matching row wins:

not in an attacking state → false. There is no fight to end.
tier below Far → false. The NPC is still being simulated in full.
no proximity measurement → false. Never hand a monster its health back on an unanswered question.
nearest player inside leashResetSqrDistance → false. Somebody is right there, whatever the network is streaming them.
otherwise → true.

ApplyAreaThreat(ICharacter, float, int)

Records a nearby cast against an NPC that is already in combat.

public void ApplyAreaThreat(ICharacter caster, float threatPoints, int resourceSpent)

Parameters

caster ICharacter

The casting character.

threatPoints float

Flat threat added, only while the NPC already has a threat table.

resourceSpent int

Resource the cast spent, weighted by the NPC's own resource weight.

Remarks

Only NPCs already in combat gain flat threat: casting near an unaware mob does not pull it. The resource record is kept regardless, and RecordResourceSpent(long, int) applies the same in-combat rule to it.

ApplyKnockback(Vector3)

Shoves this NPC across the ground: velocity (metres per second, horizontal) is added to its body and bled off over a fraction of a second, during which it does not walk under its own power.

public void ApplyKnockback(Vector3 velocity)

Parameters

velocity Vector3

The push, metres per second. Only the horizontal part is used.

Remarks

Moves the NavMesh agent, so the push follows the walkable ground and stops at walls and edges like a walk would. The caller (KnockbackHitAction) has already asked the harm rule, the evade and the incapacitation gates.

ApplyTaunt(ICharacter, float, bool, float, bool)

Taunts this NPC: threat for taunter, optionally enough to put it on top of the table, and optionally an immediate target switch.

public void ApplyTaunt(ICharacter taunter, float threatPoints, bool guaranteeTopThreat, float leadOverHighest, bool forceImmediateTargetSwitch)

Parameters

taunter ICharacter

The taunting character.

threatPoints float

Flat threat added.

guaranteeTopThreat bool

When true, adds at least enough to outscore every other entry.

leadOverHighest float

Margin above the previous highest score when guaranteeing top threat.

forceImmediateTargetSwitch bool

When true, the NPC switches to the taunter now.

Remarks

The guarantee is computed in SCORE space, not in raw points. An NPC chooses its target with GetThreatScore(long, ICharacter), which multiplies raw points by a vulnerability factor for a wounded or out-of-mana character — so a taunt that merely put the taunter above the highest RAW entry still lost to a wounded ally on the very next re-evaluation, and the forced switch hid it for exactly one switch.

The table holds raw points and no character references, so it cannot evaluate another entry's score directly — but every entry's score is at most its raw points times MaximumVulnerabilityMultiplier, so clearing that bound clears every actual score whichever entry carries it. Conservative by up to that factor and never short, which is the direction a guarantee has to err in.

The taunter's OWN multiplier is deliberately NOT used to shrink the requirement, even though it is known exactly at this instant. It is TRANSIENT — 1.5x below 30% health, gone the moment a heal lands — while the raw points granted here are permanent. Dividing by it once granted a wounded tank proportionally fewer points, and the first heal then dropped their score back under the previous top's ceiling: the boss returned to its old target on the next re-evaluation, with the forced switch masking the failure for exactly one switch. Treating the taunter's multiplier as its floor of 1 keeps the guarantee standing for every later multiplier the taunter can have.

BlinkTo(Vector3, Quaternion)

Moves this NPC to position at once (a blink), onto the nearest point of the NavMesh, facing facing. Any knockback in progress ends.

public bool BlinkTo(Vector3 position, Quaternion facing)

Parameters

position Vector3

Where to land.

facing Quaternion

The rotation to land with; only its heading is used.

Returns

bool

True when the NPC was placed on the NavMesh.

CanEnterCombatFromThreat(bool, bool, bool, bool)

The state half of the combat-entry rule, pure so it can be pinned without a scene: a threat event may start a fight only for a running brain that has an attacking state, is not already fighting, and is not evading.

public static bool CanEnterCombatFromThreat(bool hasAttackingState, bool running, bool inCombatState, bool evading)

Parameters

hasAttackingState bool

True when the NPC can fight at all.

running bool

True while the brain is prepared, enabled and not quarantined.

inCombatState bool

True while the NPC is already fighting (see IsInCombatState).

evading bool

True while the NPC is on a fight-ending leash return (see IsEvading).

Returns

bool

True when the threat may start a fight, subject to the per-character checks.

Remarks

This replaced an edge: combat used to start only when the threat table went from empty to non-empty, and a fight that ended any way but a kill left the table non-empty, so every later hit was recorded and ignored. The rule is now asked on every hit and reads only the brain's own state, so there is no edge to consume.

ChangeState(BaseAIState, List<ICharacter>)

Changes the AI state, optionally providing targets for attacking states. Handles speed and state transitions.

public void ChangeState(BaseAIState newState, List<ICharacter> targets = null)

Parameters

newState BaseAIState

The new state to transition to.

targets List<ICharacter>

Optional list of targets for attacking states.

ClearPath()

Clears the agent's path without moving it.

public void ClearPath()

ClearPhaseOverrides()

Drops every boss phase override so the archetype's own slots show through again.

public void ClearPhaseOverrides()

DecayKnockback(Vector3, float, float)

One tick of a knockback bleeding off: its speed falls by deceleration × tickDelta, its direction unchanged, and it ends at zero rather than reversing.

public static Vector3 DecayKnockback(Vector3 velocity, float deceleration, float tickDelta)

Parameters

velocity Vector3
deceleration float
tickDelta float

Returns

Vector3

Remarks

Pure, so the slide a given shove produces can be pinned without an agent.

DecideChase(Vector3)

What to do about a target the way to which may be through water: measured along the line to it, scored by AISwimRisk, and the agent's areas set to match. Asked by the attacking state before each move.

public WaterVerdict DecideChase(Vector3 targetPosition)

Parameters

targetPosition Vector3

Returns

WaterVerdict

FaceInteractor(Transform)

Turns to face a character that is interacting with this NPC and stops wandering.

public void FaceInteractor(Transform interactor)

Parameters

interactor Transform

The interacting character's transform.

FaceLookTarget(float)

Rotates the character to face the current look target smoothly.

public void FaceLookTarget(float deltaTime)

Parameters

deltaTime float

FightNeedsHandOver(bool, bool, bool)

Whether the fight in progress has to move to a different attacking state: the NPC is in an attacking state, and it is not the one AttackingState now resolves to.

public static bool FightNeedsHandOver(bool hasAttackingState, bool inAttackingState, bool inResolvedAttackingState)

Parameters

hasAttackingState bool

True when an attacking state resolves at all.

inAttackingState bool

True when the current state is an attacking state.

inResolvedAttackingState bool

True when the current state is the one AttackingState resolves to.

Returns

bool

True to hand the fight over now.

Remarks

Pure, so the rule can be pinned without a scene.

ForceTarget(ICharacter)

Forces this NPC onto a specific character immediately, entering combat if it is not already fighting.

public bool ForceTarget(ICharacter character)

Parameters

character ICharacter

The character to attack. Ignored when null or dead.

Returns

bool

True if the NPC took the new target.

Remarks

The scripted-aggro entry point, used by ApplyTauntAction. Distinct from setting Target directly, which changes who the NPC is fighting without putting it into a state that fights.

GetHealthPercent()

Returns this NPC's health as a fraction (0-1) of its maximum, or 1 when it has no health resource.

public float GetHealthPercent()

Returns

float

GetMovementProgress(float, float)

Classifies how the agent is doing against its destination, and accumulates the stuck timer.

public AIMovementProgress GetMovementProgress(float deltaTime, float tolerance = 1)

Parameters

deltaTime float

Seconds since the previous AI tick.

tolerance float

Arrival tolerance.

Returns

AIMovementProgress

The current progress classification.

Remarks

Call once per AI tick from a state that is trying to move. States that are deliberately standing still must not call it, or a stationary NPC would be reported stuck.

GetSqrDistanceToTarget()

Returns the squared distance from this NPC to its current target. Returns float.MaxValue if there is no target.

public float GetSqrDistanceToTarget()

Returns

float

HaltMovement()

Stops the NPC where it stands and forgets what it was doing, for a death.

public void HaltMovement()

Remarks

Called by SuspendForCorpse() alongside disabling the controller. Disabling stops the brain; this stops the body: the agent's path is cleared, the target and look target are dropped so nothing re-engages, and the threat table is emptied. Without it the corpse's agent kept its destination and, when the brain was later re-enabled for the next pool occupant, was still heading for wherever its killer had been standing.

HasAbilityInRange(float)

Returns true if the NPC has at least one ability with range >= the given distance that is off cooldown and meets activation conditions.

public bool HasAbilityInRange(float minRange)

Parameters

minRange float

Minimum ability range required.

Returns

bool

HasArrived(float)

True when the agent has arrived at its destination.

public bool HasArrived(float tolerance = 1)

Parameters

tolerance float

Distance from the destination that counts as arrived.

Returns

bool

True if arrived.

Remarks

Requires an actual path to exist. Without that check, an agent whose destination never took reports remainingDistance == 0 and pathPending == false — which the naive test reads as "arrived" on the very first tick.

Initialize(Vector3, Vector3[])

Initializes the controller with a home position and waypoints. Sets agent dimensions and initial state.

public void Initialize(Vector3 home, Vector3[] waypoints = null)

Parameters

home Vector3

The home position for the AI.

waypoints Vector3[]

Optional waypoints for patrol.

InitializeOnce(ICharacter)

Binds this brain to its character and registers it for TryGet lookups.

public void InitializeOnce(ICharacter character)

Parameters

character ICharacter

The NPC this brain drives.

IsEvadingRule(bool, bool, bool)

The evade rule, pure so it can be pinned without a scene: an NPC evades while a fight-ending leash return is its current state and its brain is running.

public static bool IsEvadingRule(bool leashEvade, bool running, bool inReturnHomeState)

Parameters

leashEvade bool

True when a leash sent the NPC home out of a fight.

running bool

True while the brain is prepared, enabled and not quarantined.

inReturnHomeState bool

True while the return-home state is the current state.

Returns

bool

True while the NPC must take no damage.

LeashReturnHeals(bool, bool)

Whether a leash that is walking the NPC home heals it.

public static bool LeashReturnHeals(bool enteredReturn, bool completeHealOnReturn)

Parameters

enteredReturn bool

True when the leash's transition put the return state in force.

completeHealOnReturn bool

The return state's authored heal flag.

Returns

bool

True to heal the NPC to full.

Remarks

Only a leash heals: this is asked by CheckLeash(float) and nowhere else, so the same return state picked as a calm movement (TransitionToRandomMovementState()) never heals. Every leash does — a calm drift past the leash as well as one that ends a fight — exactly as the full-leash warp always has, provided the return actually became the current state and the archetype's return state is authored to heal (CompleteHealOnReturn).

Pure, so it can be pinned without a scene.

LeashStartsEvade(bool, bool, bool)

Whether a leash that is sending the NPC home should make it evade.

public static bool LeashStartsEvade(bool isPet, bool inCombatState, bool heldThreat)

Parameters

isPet bool

True for a pet.

inCombatState bool

True when the NPC was in a combat state as the leash tripped.

heldThreat bool

True when its threat table was not empty as the leash tripped.

Returns

bool

True to evade on the way home.

Remarks

Only a leash that ends a fight: the NPC was in a combat state, or still held threat. A calm NPC that has merely drifted past its leash range walks home as attackable as it was. A pet never evades: it has no spawn-point leash, and its return is catching up with its owner. Pure, so it can be pinned without a scene.

LowIdentityBits(EntityId)

The low 32 bits of an entity ID: its index and the low bits of its type.

public static int LowIdentityBits(EntityId entityId)

Parameters

entityId EntityId

A Unity entity ID.

Returns

int

The low 32 bits, as an int.

Remarks

An entity ID is 64 bits (version, type, index). No two live objects share an index, so these bits still tell every live instance apart, and MixIdentity(int) stays a bijection over them. The version bits are left out: they only tell a destroyed object from the one that later took its index.

MayAnswerPackAlert(bool, bool, bool, bool, bool, bool, bool)

Whether a pack member may join its pack's fight against an enemy a packmate engaged.

public static bool MayAnswerPackAlert(bool hasAttackingState, bool running, bool inCombatState, bool evading, bool immortal, bool alive, bool enemyValid)

Parameters

hasAttackingState bool

True when the member can fight at all.

running bool

True while its brain is prepared, enabled and not quarantined.

inCombatState bool

True while it is already fighting.

evading bool

True while it is on a fight-ending leash return.

immortal bool

True while it cannot be hurt.

alive bool

True while it is alive.

enemyValid bool

True when the enemy is alive and in the world.

Returns

bool

True when the member joins the fight.

Remarks

The combat-entry rule a hit is asked (CanEnterCombatFromThreat(bool, bool, bool, bool)), plus the per-character checks that follow it there: the member must be alive and mortal, and the enemy a valid target. So an alert never wakes a corpse or a quarantined brain, never drags an evading member back into the fight it leashed out of, and never re-targets a member already fighting — mid-orbit and mid-flee included, which the old test of the attacking state alone yanked back into the attack.

A member strolling home as a calm movement is not evading and does answer; only a leash that ended a fight makes a return an evade. Pure, so it can be pinned.

MeasureTickSpeedSqr(Vector3, Vector3, float)

The squared speed a displacement over one tick amounts to.

public static float MeasureTickSpeedSqr(Vector3 before, Vector3 after, float tickDelta)

Parameters

before Vector3

Position at the start of the tick.

after Vector3

Position the tick actually reached, after NavMesh projection.

tickDelta float

Seconds per tick.

Returns

float

Squared metres per second; zero for a non-positive tick.

Remarks

Separated so the stuck detector's input can be asserted directly.

MixIdentity(int)

Mixes an instance ID into a key whose every bit depends on every input bit.

public static uint MixIdentity(int instanceId)

Parameters

instanceId int

A Unity instance ID, or LowIdentityBits(EntityId) of an entity ID.

Returns

uint

The mixed key.

Remarks

The "lowbias32" integer hash: xor-shifts and odd multiplies, each invertible, so the whole is a bijection on 32 bits — two instances never share a key. See IdentityKey.

NeedsAgentWrite(Vector3, Vector3, Vector3)

Whether a tick's step has to be written to the agent and the transform.

public static bool NeedsAgentWrite(Vector3 step, Vector3 agentPosition, Vector3 transformPosition)

Parameters

step Vector3

This tick's displacement.

agentPosition Vector3

Where the agent's simulation has the NPC.

transformPosition Vector3

Where the transform has it.

Returns

bool

True to write the step.

Remarks

Only when the NPC is moving, or when something other than the step has moved its transform away from where its agent believes it is. Both comparisons use Unity's approximate vector equality, a hundredth of a millimetre: far below anything a tick can show. Pure, so the rule can be pinned without an agent.

OnStartCharacter()

Called when the character starts on the client. Use for local client initialization.

public void OnStartCharacter()

OnStopCharacter()

Called when the character stops on the client. Use for local client cleanup.

public void OnStopCharacter()

OnThreatReceived(ICharacter)

Event-driven combat entry. Called by AggressionState on every hit the NPC takes, and by ApplyTaunt(ICharacter, float, bool, float, bool). Transitions to combat at once, without waiting for the next SweepForEnemies(float) physics poll, whenever the NPC is not already fighting.

public void OnThreatReceived(ICharacter attacker)

Parameters

attacker ICharacter

The character that generated the threat.

Remarks

This eliminates the biggest polling cost for non-Active NPCs: thousands of per-NPC physics OverlapSphere calls every EnemySweepRate seconds. Nearby tier NPCs rely entirely on this event to detect combat; Active tier NPCs still run SweepForEnemies for proactive (hostile faction) detection.

Called on every hit, so the cheap state checks come first: for an NPC already fighting — every hit after the first — it returns on a few property reads, before any component lookup.

PetCanAnswerAttacker(Vector3, Vector3, float, float)

Whether a pet may turn on an attacker standing at attackerPosition without breaking its owner leash to do it. Pure, so the rule can be pinned.

public static bool PetCanAnswerAttacker(Vector3 ownerPosition, Vector3 attackerPosition, float ownerLeashRange, float reach)

Parameters

ownerPosition Vector3

The pet's owner.

attackerPosition Vector3

The character that hit the pet or its owner.

ownerLeashRange float

The attacking state's OwnerLeashRange.

reach float

How far from its target the pet can fight: its preferred distance or its longest offensive reach.

Returns

bool

True when the pet may engage.

Remarks

Measured from the owner, because the owner leash is: the attacking state calls the pet back once the PET is ownerLeashRange from its owner. The pet can hit from reach short of its target, so an attacker within the leash plus that reach can be answered from inside the leash; one further out cannot, and the pet would break off before landing a blow. A leash of zero or less means no owner leash.

PetStanceAllowsAutoEngage(bool)

Returns whether this NPC's pet stance permits engaging on its own. Always true for anything that is not a pet.

public bool PetStanceAllowsAutoEngage(bool requiresAggressive)

Parameters

requiresAggressive bool

True to require the Aggressive stance (hunting for a fight); false to accept anything except Passive (fighting back).

Returns

bool

True if the NPC may engage.

PhaseFraction(uint, uint)

A fraction in [0, 1) drawn from key, different for each salt, so one identity can seed several independent phases.

public static float PhaseFraction(uint key, uint salt)

Parameters

key uint

An identity key from MixIdentity(int).

salt uint

Distinguishes the phases drawn from one key.

Returns

float

The fraction.

PickBestAbility(float)

Selects the best ability to use against the current target from the NPC's known abilities.

When an AbilityRotation is assigned, it is evaluated first. If it returns an ability, that ability is used. If no rotation entry matches and FallbackToDefault is true, the default scoring-based picker runs as a fallback.

Prefers abilities whose range covers the current distance. Among those, picks one at random weighted toward longer-cooldown (typically stronger) abilities. Returns null if no ability is usable (all on cooldown, out of resources, or no abilities known).

public Ability PickBestAbility(float preferredMaxRange = 3.4028235E+38)

Parameters

preferredMaxRange float

Maximum desired range. Abilities with range beyond this are still considered but deprioritized.

Returns

Ability

The chosen ability, or null if nothing is available.

PickBestAbility(float, Func<Ability, bool>)

Selects the best ability to use against the current target, optionally restricted to abilities matching a predicate.

public Ability PickBestAbility(float preferredMaxRange, Func<Ability, bool> filter)

Parameters

preferredMaxRange float

Maximum desired range.

filter Func<Ability, bool>

Optional predicate an ability must satisfy to be considered. Used by HealerAttackingState to keep heals out of the damage rotation.

Returns

Ability

The chosen ability, or null if nothing is available.

PickNearestWaypoint()

Picks the nearest waypoint to the current position and sets it as the destination.

public bool PickNearestWaypoint()

Returns

bool

True if a waypoint destination was set.

PickScoredAbility(float, Func<Ability, bool>, float)

Scores every usable known ability against a subject at the given squared distance and returns the highest scorer.

public Ability PickScoredAbility(float sqrDistanceToSubject, Func<Ability, bool> filter, float jitter)

Parameters

sqrDistanceToSubject float

Squared distance to whatever the ability will be aimed at.

filter Func<Ability, bool>

Optional predicate an ability must satisfy. Null accepts all.

jitter float

Maximum random score jitter, for variety.

Returns

Ability

The best-scoring usable ability, or null.

Remarks

Shared by the default enemy picker and by HealerAttackingState's heal picker, which scores against an ally's distance rather than the target's. Both previously carried their own near-identical copy of this loop.

ResolveAbilityReach(Ability)

How far ability can hit something from, for this NPC's body size.

public float ResolveAbilityReach(Ability ability)

Parameters

ability Ability

Returns

float

Remarks

Always use this rather than Range in AI code: the raw range is zero for anything that does not travel. See AIAbilityReach.

ResolveLodPhase(int, int)

The phase of the LOD stagger, in AI ticks.

public static int ResolveLodPhase(int staggerID, int ticksPerAiUpdate)

Parameters

staggerID int

The NPC's stagger slot.

ticksPerAiUpdate int

Network ticks per brain tick.

Returns

int

The LOD phase.

Remarks

The part of the stagger the brain-tick phase did not use. The brain tick already takes staggerID % ticksPerAiUpdate; the LOD gate used to add the whole staggerID again, and when the two moduli share a factor the phases are correlated: with a brain every 4th network tick and an Active interval of 2, the combinations of the two phases fill only 4 of the 8 network-tick slots in each cycle, doubling the per-tick peak. Taking the quotient instead makes the two phases independent, so a population spreads over every slot.

Pure, so the spread can be asserted directly.

ResolveLodTier(AILodSettings, bool, float)

The tier rule, as a pure function so it is testable without a NetworkManager.

public static AILodTier ResolveLodTier(AILodSettings settings, bool hasProximityMeasurement, float nearestPlayerSqrDistance)

Parameters

settings AILodSettings

Authored LOD bands, or null.

hasProximityMeasurement bool

False when nothing has measured the nearest player yet.

nearestPlayerSqrDistance float

Squared distance to the nearest player.

Returns

AILodTier

The tier to run at.

Remarks

Truth table, first matching row wins:

no LOD settings → Active. Nothing has authored a throttle for this NPC.
no proximity measurement → Active. An unanswered question is not permission to suspend a brain; the answer arrives within one scheduling pass, and running one extra tier for half a second costs far less than a monster that stops thinking with a player in front of it.
measured → the authored distance bands, infinity (an empty scene) landing in Dormant.

ResolveTickHeading(Quaternion, Vector3, float, float, out Quaternion)

Turns a heading toward the direction of travel, bounded by an angular speed.

public static bool ResolveTickHeading(Quaternion current, Vector3 velocity, float angularSpeed, float tickDelta, out Quaternion result)

Parameters

current Quaternion

The current rotation.

velocity Vector3

The agent's velocity.

angularSpeed float

Maximum turn, in degrees per second.

tickDelta float

Seconds per tick.

result Quaternion

The rotation to apply.

Returns

bool

True if the heading changed.

Remarks

Mirrors what NavMeshAgent.updateRotation does per frame, on the tick instead. Vertical velocity is ignored so a slope does not pitch the character, and a velocity below HEADING_SPEED_THRESHOLD leaves the heading alone: an agent braking to a stop or being nudged by avoidance must not spin to face the nudge.

ResolveTickStep(Vector3, float)

The displacement one tick of travel at velocity covers.

public static Vector3 ResolveTickStep(Vector3 velocity, float tickDelta)

Parameters

velocity Vector3
tickDelta float

Returns

Vector3

Remarks

Separated so the tick-uniformity StepAgent relies on can be asserted directly.

ResolveTicksPerAiUpdate(float, float)

Network ticks per AI tick for a requested brain rate: the nearest whole divisor of the network tick. Pure, and shared with the packs AIBrainHost ticks, so a pack thinks on the same cadence as its members.

public static int ResolveTicksPerAiUpdate(float aiTickRate, float networkTickDelta)

Parameters

aiTickRate float

The requested rate, in hertz.

networkTickDelta float

Seconds per network tick; 1/30 when not positive.

Returns

int

Network ticks between AI ticks, at least 1.

Resume()

Resumes the agent's movement.

public void Resume()

ResumeAfterCorpse()

Starts a brain that SuspendForCorpse() stopped.

public void ResumeAfterCorpse()

RollAimForCast(AIAimProfile, float)

Rolls the aim error for a cast that is about to begin, and notes what it is being cast with.

public void RollAimForCast(AIAimProfile profile, float projectileSpeed)

Parameters

profile AIAimProfile

The archetype's aim profile, or null for exact aim.

projectileSpeed float

The ability's travel speed, or 0 for an instant ability.

Remarks

Once per cast, never per tick. The NPC's seeded RNG is shared with cooldown jitter, target selection, movement-variety rolls, wander rates and leash timing. Drawing from it on every network tick would advance that stream thirty times a second and change the behaviour of every one of those, none of which this feature is tuning. Once per cast is also what the design wants: the error belongs to the shot, not to the tick, and holding it is what makes an inaccurate NPC read as aiming badly rather than spraying.

A null profile rolls nothing, which is the exact-aim default every archetype without an aim profile keeps.

SetPhaseOverrides(BaseAIState, AIBehaviorTree, AIAbilityRotation)

Puts a boss phase's overrides in front of the archetype's slots. A null argument leaves that slot's current override in place, so a later phase that only replaces the rotation keeps the attacking state an earlier phase installed.

public void SetPhaseOverrides(BaseAIState attackingState, AIBehaviorTree behaviorTree, AIAbilityRotation abilityRotation)

Parameters

attackingState BaseAIState

Attacking state for the phase, or null to keep the current one.

behaviorTree AIBehaviorTree

Behavior tree for the phase, or null to keep the current one.

abilityRotation AIAbilityRotation

Ability rotation for the phase, or null to keep the current one.

Remarks

An attacking-state override takes over the fight at once. AttackingState reads the override, but the NPC keeps running whichever attacking state it entered until something re-enters one. What did, by accident, was the out-of-combat enemy sweep: it tested only "is the current state the resolved attacking state", so after an override it ran against the old one and, a sweep interval later and in the Active tier only, re-entered the new one with a fresh target pick and the cast interrupted. The sweep no longer runs in any combat state (SweepMayRun(bool, bool, bool)), so the swap now happens here, when the phase starts, through FishMMO.Server.Implementation.World.SceneServer.AI.AIController.HandOverFight(), which keeps the target and the cast in progress. A boss not in its attacking state is left alone: a combat sub-state returns to AttackingState and so picks the override up on its own, and a boss out of combat enters it the next time it engages.

SetRandomDestination(float)

Sets a random destination within a radius around the current position.

public bool SetRandomDestination(float radius = 5)

Parameters

radius float

Radius to randomize destination.

Returns

bool

SetRandomHomeDestination(float)

Sets a random destination within a radius around the home position.

public bool SetRandomHomeDestination(float radius = 5)

Parameters

radius float

Radius to randomize destination.

Returns

bool

SetThrottledDestination(Vector3)

Throttled destination setter. Only calls UnityEngine.AI.NavMeshAgent.SetDestination(UnityEngine.Vector3) if enough time has elapsed since the last repath (controlled by RepathInterval). Use this for ongoing movement toward a moving target (chase, orbit, retreat) to prevent path recalculation spam. For one-time destinations (waypoint arrival, warp), use UnityEngine.AI.NavMeshAgent.SetDestination(UnityEngine.Vector3) directly.

public bool SetThrottledDestination(Vector3 position)

Parameters

position Vector3

The world position to navigate toward.

Returns

bool

True if the destination was updated, false if throttled.

ShouldAttemptReseat(ref float, float, float)

Counts down between off-mesh re-seat attempts and reports when one is due.

public static bool ShouldAttemptReseat(ref float timer, float tickDelta, float interval)

Parameters

timer float

Seconds until the next attempt; rearmed to interval when one is due.

tickDelta float

Seconds since the previous call.

interval float

Seconds between attempts.

Returns

bool

True when an attempt should be made now.

Remarks

Separated so the cadence can be asserted directly. The first call of an episode is due at once (the timer is zero when the agent is on the mesh); every later one waits interval, so a hopeless NPC costs one widening NavMesh sample a second, not thirty.

ShouldStepBody(AILodTier, bool)

Whether this network tick should advance the NPC's body — off-mesh recovery, the agent step, facing and aim.

public static bool ShouldStepBody(AILodTier tier, bool hasSomewhereToGo)

Parameters

tier AILodTier

The NPC's current LOD tier.

hasSomewhereToGo bool

True when the agent has a path or is traversing a link. Only consulted when Dormant.

Returns

bool

True to step the body this tick.

Remarks

Every tier but Dormant always does. A Dormant NPC does only while it still has a path or is on an off-mesh link: nobody is within the Far band to see it, its brain does not run, and an idle agent needs nothing. Pure, so the rule can be pinned without an agent.

Stop()

Stops the agent's movement.

public void Stop()

SuspendForCorpse()

Stops the brain for a corpse: no thinking, no movement, no target, no threat.

public bool SuspendForCorpse()

Returns

bool

True when the brain was running and has been stopped by this call.

SweepMayRun(bool, bool, bool)

Whether the out-of-combat enemy sweep may run for an NPC in this state.

public static bool SweepMayRun(bool hasAttackingState, bool returningHome, bool inCombatState)

Parameters

hasAttackingState bool

True when the NPC can fight at all.

returningHome bool

True while the return-home state is the current state.

inCombatState bool

True while the current state is part of a fight.

Returns

bool

True when the sweep may run.

Remarks

Never while going home, and never in a fight — which is any state that keeps the combat target (IsInCombatState): the attacking state and every combat sub-state. The sweep is how a calm NPC notices an enemy; an NPC already fighting has a target, a threat table and a re-evaluation timer for that. Pure, so it can be pinned without a scene.

TransitionToIdleState()

Transitions to the idle state.

public void TransitionToIdleState()

TransitionToNextWaypoint()

Transitions to the next waypoint in the waypoint array.

public bool TransitionToNextWaypoint()

Returns

bool

TransitionToRandomMovementState()

Transitions to a random movement state from the available movement states.

public virtual void TransitionToRandomMovementState()

TryFindShore(out Vector3)

The nearest land to the NPC, for one in the water that has decided against it.

public bool TryFindShore(out Vector3 shore)

Parameters

shore Vector3

Returns

bool

TryGetNearestPlayerSqrDistance(out float)

Squared distance from this NPC to the nearest player in its scene.

public bool TryGetNearestPlayerSqrDistance(out float sqrDistance)

Parameters

sqrDistance float

Squared distance to the nearest player; infinity when the scene holds none.

Returns

bool

True when the measurement is valid.

Remarks

From ObserverStreamingRegistry, which measures viewer-to-object distance for every pair it considers anyway, before it applies any range or budget filter. That is a PROXIMITY question and this is the only place the server answers it honestly.

It used to be answered from NetworkObject.Observers. Observer membership is a BANDWIDTH decision — ObserverBudgetCondition admits the top thirty monsters per viewer and no more — so a monster evicted from every viewer's budget reported "no player is anywhere near me" while standing in the middle of a raid, and the tier machinery below full-healed it, cleared its threat table and reset its boss phases on the strength of it.

Returns false when no pass has measured this NPC yet (it registered between two passes, or the registry is not running at all, as in the simulation harness scenes). Callers must not read false as "nobody is near" — see ResolveLodTier(AILodSettings, bool, float) and AllowsLeashReset(AILodTier, bool, bool, float, float), both of which treat it as an unanswered question.

TryMatchClimbable(IReadOnlyList<SceneClimbable>, Vector3, Vector3, out int, out bool)

The climbable whose NavMesh link runs from start to end, and whether the link is taken upward (foot to landing) or down: the one whose ends lie nearest both, within ClimbLinkMatchMetres of each. Lowest index on a tie, so the answer never depends on anything else.

public static bool TryMatchClimbable(IReadOnlyList<SceneClimbable> climbables, Vector3 start, Vector3 end, out int index, out bool upward)

Parameters

climbables IReadOnlyList<SceneClimbable>
start Vector3
end Vector3
index int
upward bool

Returns

bool

TryMoveTo(Vector3, bool, float)

Asks the agent to move to a world position, reporting whether the path actually reaches it.

public AIMovementResult TryMoveTo(Vector3 destination, bool throttle = true, float sampleRadius = 2)

Parameters

destination Vector3

Desired world position.

throttle bool

True to respect RepathInterval. Use for ongoing movement toward something that moves; pass false for one-shot destinations such as a waypoint or a spawn point, where a silently dropped request means the NPC never sets off at all.

sampleRadius float

Initial NavMesh sample radius.

Returns

AIMovementResult

What happened.

TryRecoverFromStuck(Vector3)

Attempts to free a stuck NPC, escalating with each call within the same episode.

public bool TryRecoverFromStuck(Vector3 fallback)

Parameters

fallback Vector3

Where to go if the original destination cannot be recovered — a pet's owner, an NPC's home. Pass the NPC's own position to mean "just get unstuck where you are".

Returns

bool

True if a recovery action was taken.

Remarks

First a nudge: re-sample the destination from a wider radius and repath, which clears the common case of two agents wedged against each other or a destination that sampled onto the wrong side of a wall. Then, once StuckWarpTimeout has elapsed, a warp — the only remedy for genuinely unreachable geometry.

Warping is a last resort rather than the first move on purpose: it is visible to players, so an NPC should be seen to try to walk before it blinks.

TrySampleNavMesh(Vector3, out Vector3, float, int)

Places a world position onto the NavMesh, widening the search until it lands or the attempts run out.

public static bool TrySampleNavMesh(Vector3 position, out Vector3 result, float initialRadius = 2, int areaMask = 0)

Parameters

position Vector3

The desired world position.

result Vector3

The nearest position actually on the NavMesh.

initialRadius float

Radius for the first attempt.

areaMask int

The areas to sample; land only (LandAreas) when 0, so nothing is put on a sea floor. Not -1 for that: -1 is UnityEngine.AI.NavMesh.AllAreas, which a swimmer immune to lava really does walk.

Returns

bool

True if a NavMesh position was found.

Remarks

A single fixed-radius sample is the difference between "the NPC walks to a slightly different spot" and "the NPC does not move at all", and the old call sites all took the second outcome silently.

WarpTo(Vector3)

Places the agent at a world position, using UnityEngine.AI.NavMeshAgent.Warp(UnityEngine.Vector3) so the agent's internal NavMesh position is updated rather than only its transform.

public bool WarpTo(Vector3 position)

Parameters

position Vector3

The world position to place the agent at.

Returns

bool

True if the agent was placed on the NavMesh.

Remarks

Required for object pooling. A recycled NPC is reactivated at a new position, and assigning transform.position alone leaves the agent believing it is still where the previous occupant died — it then either refuses to path or walks back toward the old location.

Events

OnPetTargetChanged

The current target for the AI (e.g., enemy, destination). Setting this property updates the agent's destination.

public static event Action<Pet, ICharacter> OnPetTargetChanged

Event Type

Action<Pet, ICharacter>