Skip to content

t1k:unity:dots-ai:core

FieldValue
Moduledots-ai
Version3.30.3
Effortmedium
Tools—
/t1k:unity:dots-ai:core

DOTS AI Core — Perception, Alert, Leash, Stealth, Party

Section titled “DOTS AI Core — Perception, Alert, Leash, Stealth, Party”

Package: com.the1studio.dots-ai — namespace DOTSAI.* Note: This skill covers DOTSAI core systems. For BDP behavior trees, see: dots-ai-behavior-designer-pro · dots-ai-bdp-tactical-pack · dots-ai-bdp-formations-pack

  • Implementing alert escalation (Unaware → Suspicious → Alert → Combat)
  • Adding AI leash / home-radius aggro reset
  • Building party formations and party-buff systems
  • Implementing stealth detection, line-of-sight, detection cone
  • Setting up per-entity perception and threat tracking
  • Assigning agents to queued work, claiming/releasing work candidates, or adding a new WorkTaskKind
ComponentTypePurpose
AlertLevelIComponentData + IEnableableComponentAlertTier Level, Entity DetectedEntity, float AlertTimer
AlertTierenumUnaware=0, Suspicious=1, Alert=2, Combat=3
AILeashIComponentDatafloat3 HomePosition, float LeashRadius, bool Initialized
PartyFormationIComponentDataFormationType Type, float Spacing; baked on every member
PartyMemberIComponentDataMarks entity as party member
PartyLeaderTagIComponentData (tag)Marks party leader
PartyBuffIComponentDataPassive bonus leader grants members in formation
public enum FormationType { Line, Wedge, Circle, Column }
SystemGroupRole
AlertDecaySystemAISystemGroupDecrements AlertTimer; decays AlertTier on zero; disables component at Unaware
AlertTriggerSystemAISystemGroupEscalates AlertLevel on player/target detection
AILeashInitSystemAISystemGroupInitializes HomePosition on first tick
AIRespawnResetSystemAISystemGroupClears aggro state on respawn
StealthVisibilitySystemAISystemGroupChecks LOS + detection range for stealth entities
PartyFormationSystemAISystemGroupPositions members relative to leader per FormationType
AttackObjectiveTargetingSystemAISystemGroupScores objective vs. ally candidates (weighted distance) for siege attackers

Burst-compatible static utilities shared across AI systems and BDP task systems (no managed types). Always reuse these instead of re-implementing the scan/flee math inline.

MethodSignaturePurpose
TryFindNearestEnemybool TryFindNearestEnemy(in DynamicBuffer<PerceivedEntity> perceived, byte myTeam, bool requireVisible, out Entity nearest, out float nearestDist)Scans a PerceivedEntity buffer for the nearest enemy; skips same-team entries; optionally skips non-visible. Returns true only when a real enemy was found (uses nearest != Entity.Null internally, NOT a sentinel overload).
ComputeFleePositionfloat3 ComputeFleePosition(float3 currentPos, float3 enemyDirection, float fleeDistance)Computes a retreat position away from the nearest enemy; guards zero-length direction with a (0,0,-1) fallback via GameplayConstants.DirectionEpsilon.

AlertTriggerSystem and StealthVisibilitySystem both call AIHelpers.TryFindNearestEnemy — the previously-duplicated closest-enemy scan loops are now consolidated here (DRY, Wave A).

Code patterns for: 4-tier alert decay (AlertDecaySystem), AILeash enforcement (clears Threat/Aggro buffers + retargets home on leash-radius breach), and party formation positioning (per-member offset from leader). Full code: references/common-patterns.md.

A genre-neutral “which agent does which job” queue. Candidate entities (a farm tile, a loose carry item, a fishing spot) advertise a WorkTaskKind; agents claim one; a genre-specific execution system applies it. This package holds zero farming/fishing knowledge — the state→verb mapping and the mutation both live in the consuming package (for farming, see t1k-unity-dots-core-farming).

TypeKindPurpose
WorkCandidateTagIComponentDataMarks an entity as offering work. One Kind field — see the collision gotcha
WorkCandidateDirtyIEnableableComponentPresent-but-disabled by default. Enable it when an entity’s work-eligibility changes; WorkCandidateRefreshSystem re-buckets it next pass instead of rescanning everything every tick
WorkTargetIComponentDataEntity ClaimedBy — the claim lock keeping two agents off one candidate
AgentAssignmentIComponentDataWorkTaskKind Kind, Entity ClaimedTarget, bool Assignable
WorkTaskKindenum, in DOTSCore.Workers (not this package)None=0, Supply, HarvestMark, Carry, Water, Plant, Harvest, Weed, Pluck, Wander=9, Fishing, Interact

Systems: WorkAssignmentSystem (priority walk → assigns a kind + claims a target) and WorkCandidateRefreshSystem (drains dirty flags → re-buckets into queues).

WorkClaimRelease.Release — the completion primitive

Section titled “WorkClaimRelease.Release — the completion primitive”

Task completion is not automatic. WorkAssignmentSystem assigns; nothing releases until an execution system decides a claim is done. This is that primitive — for any kind whose execution finishes synchronously within one tick.

WorkClaimRelease.Release(
ref ComponentLookup<WorkTarget> targetLookup,
ref ComponentLookup<WorkCandidateDirty> dirtyLookup,
ref AgentAssignment assignment);

Three writes, in order: clear the claimed target’s WorkTarget.ClaimedBy → enable its WorkCandidateDirty → reset assignment.Kind = None and ClaimedTarget = Entity.Null.

  • It takes ref AgentAssignment, not RefRW<AgentAssignment>, deliberately — a plain ref is callable both from a live SystemAPI.Query<RefRW<AgentAssignment>>() iteration (pass ref assignment.ValueRW) and from a bare EntityManager.GetComponentData/SetComponentData round-trip in a unit test, with no hand-built system-bound RefRW<T>.
  • The dirty flag is set unconditionally, not only when Kind changed. A completed claim must return to circulation even when the candidate’s kind is identical (a perpetual fishing tile; a harvest tile whose ReadyToHarvest the yield system hasn’t cleared yet). The claimed-tile skip in the refresh path only fires while ClaimedBy is non-null, so clearing it here is precisely what re-admits the candidate.

Multi-frame work does NOT use this primitive

Section titled “Multi-frame work does NOT use this primitive”

Release is scoped to single-tick tasks resolved via WorkTarget. A haul trip is inherently multi-frame and governed by WorkerHaul, with no WorkTarget involvement — so WorkTaskKind.Carry is released by DOTSCore.Logistics.WorkerHaulReleaseSystem instead. That is not duplication; the two cover different lifetimes. See t1k-unity-dots-core-logistics.

DirectionPackageDetail
Depends onDOTSCore baseLocalTransform, ECB, SystemAPI
Depends onDOTSCore.StatsHealth/Experience for damage-based aggro integration
Used byDOTSCombatAttack targeting reads AlertLevel
Used byDOTSBDPBehavior tree checks AlertLevel for combat branch
Depends onDOTSCore.WorkersWorkTaskKind + AgentAssignment live there, not in this package
Paired withDOTSCore.LogisticsWorkerHaulReleaseSystem releases the multi-frame Carry kind that WorkClaimRelease deliberately does not cover
Consumed bygenre packages (e.g. DOTSFarming)They supply the state→kind mapping and the task mutation; this package stays genre-neutral
  • BattleDemo2D — enemies escalate Alert on detection; party formations for mob groups
  • ChaosForgeDemo — AILeash prevents farm-camping single rooms; alert decay enables stealth evasion
  • BackpackBattlefield — party buff scales with FormationType (wedge = +attack damage)
  • AlertLevel is IEnableableComponent — disabling via EnabledRefRW is cheaper than add/remove. NEVER use GetSingleton / HasSingleton on IEnableableComponent types. Use WithPresent<AlertLevel>() to include disabled entities in jobs that need to SET the alert.
  • AILeash.Initialized flag required — without it, HomePosition overwrites every frame. Self-init pattern: if !leash.Initialized then set leash.HomePosition = currentPos; leash.Initialized = true; in AILeashInitSystem.OnUpdate.
  • PartyFormation baked on every member, not leader — this is intentional for query efficiency. Do not try to centralize formation data on the leader entity; the query iterates members directly.
  • StealthVisibilitySystem needs explicit LOS — distance-only detection fails against obstacles. The system performs spatial hash or raycast checks. Pure distance checks are insufficient for stealth.
  • [RequireMatchingQueriesForUpdate] missing — AlertDecaySystem and AlertTriggerSystem are early-game empty-query candidates. Add [RequireMatchingQueriesForUpdate] to skip frames when no entities have AlertLevel (W4.4 finding).
  • AttackObjectiveTargetingSystem.GatherAlliesJob excludes corpses via [WithNone(typeof(DeadTag))] — targeting/scoring jobs that gather allies (or enemies) MUST carry [WithNone(DeadTag)] or they fold dead-but-not-yet-cleaned entities into formation/target math (units run toward corpses, slots reserved for the dead). Mirror this on every gather job in the objective/targeting pipeline.
  • PartyFormationSystem Circle divides by ACTUAL live-follower count, not a hardcoded 8 — a Pass-0 NativeHashMap<int,int> counts live followers per PartyId, then the Circle case uses that count (≥1) to space slots. The old hardcoded / 8 made followers 9+ stack on top of slot 0 (silent overlap). For the allocator here use Allocator.Temp (Burst-safe on the main thread, supports Free()), NOT WorldUpdateAllocator — see the cross-cutting WorldUpdateAllocator→Allocator.Temp NRE fix this also carried.
  • PerceivedEntity.Target == Entity.Null is NOT a valid “no enemy found” sentinel — a PerceivedEntity entry can legitimately carry Target == Entity.Null (the perception pipeline records a detected threat whose resolved entity is null, e.g. an unresolved/destroyed-this-frame target). AlertTriggerSystem originally scanned the PerceivedEntity buffer for the closest visible enemy into closestEnemy = pe.Target, then short-circuited with if (closestEnemy == Entity.Null) return;. Because a found enemy could have Target == Entity.Null, that guard returned early even when a real enemy was found → all tier classification stayed stuck at Unaware (silent, no error, full perception→alert path dead). Fix: track a dedicated bool hasEnemy = false; set to true inside the closest-enemy branch and gate on if (!hasEnemy) return; — never overload an Entity.Null comparison as the loop’s “found anything?” flag. General rule: when reducing a buffer to “did we find a qualifying element?”, use a separate bool, not a sentinel value the element type can legitimately hold. As of Wave A this scan lives in AIHelpers.TryFindNearestEnemy (returns bool hasEnemy), and both AlertTriggerSystem and StealthVisibilitySystem consume it — call the helper rather than re-rolling the loop, so the sentinel pitfall stays fixed in one place.

Wave A/B rename & obsolete-alias hard rules (dots-ai 3.0.0)

Section titled “Wave A/B rename & obsolete-alias hard rules (dots-ai 3.0.0)”

AttackObjectiveConfig.HeroWeight → AllyWeight and AttackObjectiveHeroTag → AttackObjectiveAllyTag (the AI module is genre-neutral) both ship [Obsolete] forwarding aliases — new code must use the renamed form. Full rename detail, the weighted-distance formula, and the [MovedFrom] scope caveat (covers authoring MonoBehaviours only, not the renamed component struct): references/common-patterns.md § “Wave A/B rename & obsolete-alias gotchas”.