t1k:unity:dots-ai:core
| Field | Value |
|---|---|
| Module | dots-ai |
| Version | 3.30.3 |
| Effort | medium |
| Tools | — |
How to invoke
Section titled “How to invoke”/t1k:unity:dots-ai:coreDOTS AI Core — Perception, Alert, Leash, Stealth, Party
Section titled “DOTS AI Core — Perception, Alert, Leash, Stealth, Party”Package:
com.the1studio.dots-ai— namespaceDOTSAI.*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
When This Skill Triggers
Section titled “When This Skill Triggers”- 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
Public Components
Section titled “Public Components”| Component | Type | Purpose |
|---|---|---|
AlertLevel | IComponentData + IEnableableComponent | AlertTier Level, Entity DetectedEntity, float AlertTimer |
AlertTier | enum | Unaware=0, Suspicious=1, Alert=2, Combat=3 |
AILeash | IComponentData | float3 HomePosition, float LeashRadius, bool Initialized |
PartyFormation | IComponentData | FormationType Type, float Spacing; baked on every member |
PartyMember | IComponentData | Marks entity as party member |
PartyLeaderTag | IComponentData (tag) | Marks party leader |
PartyBuff | IComponentData | Passive bonus leader grants members in formation |
public enum FormationType { Line, Wedge, Circle, Column }Public Systems
Section titled “Public Systems”| System | Group | Role |
|---|---|---|
AlertDecaySystem | AISystemGroup | Decrements AlertTimer; decays AlertTier on zero; disables component at Unaware |
AlertTriggerSystem | AISystemGroup | Escalates AlertLevel on player/target detection |
AILeashInitSystem | AISystemGroup | Initializes HomePosition on first tick |
AIRespawnResetSystem | AISystemGroup | Clears aggro state on respawn |
StealthVisibilitySystem | AISystemGroup | Checks LOS + detection range for stealth entities |
PartyFormationSystem | AISystemGroup | Positions members relative to leader per FormationType |
AttackObjectiveTargetingSystem | AISystemGroup | Scores objective vs. ally candidates (weighted distance) for siege attackers |
Shared Helpers — DOTSAI.AIHelpers
Section titled “Shared Helpers — DOTSAI.AIHelpers”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.
| Method | Signature | Purpose |
|---|---|---|
TryFindNearestEnemy | bool 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). |
ComputeFleePosition | float3 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).
Common Patterns
Section titled “Common Patterns”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.
The generic work queue (DOTSAI.WorkQueue)
Section titled “The generic work queue (DOTSAI.WorkQueue)”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).
| Type | Kind | Purpose |
|---|---|---|
WorkCandidateTag | IComponentData | Marks an entity as offering work. One Kind field — see the collision gotcha |
WorkCandidateDirty | IEnableableComponent | Present-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 |
WorkTarget | IComponentData | Entity ClaimedBy — the claim lock keeping two agents off one candidate |
AgentAssignment | IComponentData | WorkTaskKind Kind, Entity ClaimedTarget, bool Assignable |
WorkTaskKind | enum, 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, notRefRW<AgentAssignment>, deliberately — a plainrefis callable both from a liveSystemAPI.Query<RefRW<AgentAssignment>>()iteration (passref assignment.ValueRW) and from a bareEntityManager.GetComponentData/SetComponentDataround-trip in a unit test, with no hand-built system-boundRefRW<T>. - The dirty flag is set unconditionally, not only when
Kindchanged. A completed claim must return to circulation even when the candidate’s kind is identical (a perpetual fishing tile; a harvest tile whoseReadyToHarvestthe yield system hasn’t cleared yet). The claimed-tile skip in the refresh path only fires whileClaimedByis 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.
Cross-Package Interactions
Section titled “Cross-Package Interactions”| Direction | Package | Detail |
|---|---|---|
| Depends on | DOTSCore base | LocalTransform, ECB, SystemAPI |
| Depends on | DOTSCore.Stats | Health/Experience for damage-based aggro integration |
| Used by | DOTSCombat | Attack targeting reads AlertLevel |
| Used by | DOTSBDP | Behavior tree checks AlertLevel for combat branch |
| Depends on | DOTSCore.Workers | WorkTaskKind + AgentAssignment live there, not in this package |
| Paired with | DOTSCore.Logistics | WorkerHaulReleaseSystem releases the multi-frame Carry kind that WorkClaimRelease deliberately does not cover |
| Consumed by | genre packages (e.g. DOTSFarming) | They supply the state→kind mapping and the task mutation; this package stays genre-neutral |
Demo Precedents
Section titled “Demo Precedents”- 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)
Hard rules
Section titled “Hard rules”- AlertLevel is IEnableableComponent — disabling via
EnabledRefRWis cheaper than add/remove. NEVER useGetSingleton/HasSingletonon IEnableableComponent types. UseWithPresent<AlertLevel>()to include disabled entities in jobs that need to SET the alert. - AILeash.Initialized flag required — without it,
HomePositionoverwrites every frame. Self-init pattern: if!leash.Initializedthen setleash.HomePosition = currentPos; leash.Initialized = true;inAILeashInitSystem.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 —
AlertDecaySystemandAlertTriggerSystemare early-game empty-query candidates. Add[RequireMatchingQueriesForUpdate]to skip frames when no entities have AlertLevel (W4.4 finding). AttackObjectiveTargetingSystem.GatherAlliesJobexcludes 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.PartyFormationSystemCircle divides by ACTUAL live-follower count, not a hardcoded 8 — a Pass-0NativeHashMap<int,int>counts live followers perPartyId, then the Circle case uses that count (≥1) to space slots. The old hardcoded/ 8made followers 9+ stack on top of slot 0 (silent overlap). For the allocator here useAllocator.Temp(Burst-safe on the main thread, supportsFree()), NOTWorldUpdateAllocator— see the cross-cuttingWorldUpdateAllocator→Allocator.TempNRE fix this also carried.PerceivedEntity.Target == Entity.Nullis NOT a valid “no enemy found” sentinel — aPerceivedEntityentry can legitimately carryTarget == Entity.Null(the perception pipeline records a detected threat whose resolved entity is null, e.g. an unresolved/destroyed-this-frame target).AlertTriggerSystemoriginally scanned thePerceivedEntitybuffer for the closest visible enemy intoclosestEnemy = pe.Target, then short-circuited withif (closestEnemy == Entity.Null) return;. Because a found enemy could haveTarget == Entity.Null, that guard returned early even when a real enemy was found → all tier classification stayed stuck atUnaware(silent, no error, full perception→alert path dead). Fix: track a dedicatedbool hasEnemy = false;set totrueinside the closest-enemy branch and gate onif (!hasEnemy) return;— never overload anEntity.Nullcomparison 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 inAIHelpers.TryFindNearestEnemy(returnsbool hasEnemy), and bothAlertTriggerSystemandStealthVisibilitySystemconsume 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”.