t1k:unity:dots-combat:core
| Field | Value |
|---|---|
| Module | dots-combat |
| Version | 3.33.3 |
| Effort | medium |
| Tools | — |
Keywords: AttackConfig, BattleState, build cost, BuildRequest, CCMasks, combat, combat formulas, CombatAuthoring, CombatConstants, CurrencyId, damage, DamageEvent, dead tag, DeadTag, DemolishRequest, DerivedCombatStats, DerivedStats, DerivedStatsSystem, DerivedStatsSystem, DOTSEconomy, HealEvent, health, HitFlash, HitFlashTimer, invulnerable, kill reward, KillRewardCurrency, knockback, RangedAttack, RangedAttackConfig, RangedAttackTag, structures, WalletEntry, WalletTransaction
How to invoke
Section titled “How to invoke”/t1k:unity:dots-combat:coreDOTS Combat Core — Foundations
Section titled “DOTS Combat Core — Foundations”Package: com.the1studio.dots-combat | Namespace: DOTSCombat.*
Split from t1k:unity:dots-combat:rpg (Wave 2). For auto-battler or survivor → t1k:unity:dots-combat:gamemodes. For boss → t1k:unity:dots-combat:boss.
Overview
Section titled “Overview”| Module | Key Types |
|---|---|
| Combat (28c/19s) | Health, Mana, Shield, DamageEvent, HealEvent, StatusEffect, DeadTag, InvulnerableTag, KnockbackEvent, BattleState, AttackConfig, OnHitEffect, OnDeathEffect, AuraEffect |
| Skills (11c/8s) | SkillSlotState, SkillSlotConfig, ActiveCastState, ProjectileData, ParabolicArc, AreaEffect, HomingTarget, SkillBehaviorType, RangedAttackConfig (monolithic SkillSlot REMOVED — see Gotcha 9) |
| Synergy/Trait (5c/3s) | TraitEntry, SynergyDefinition, ActiveSynergy, TeamSynergyState, SynergyModifierSource |
| Talent Tree (5c/2s) | TalentNode, TalentProgress, TalentPoints, TalentUnlockRequest, TalentEvent |
| Summon (5c/4s) | SummonConfig, SummonState, SummonRequest, SummonEvent, SummonedByTag |
Stat pipeline: BaseStats → StatModifier[] → DerivedCombatStats / DerivedResourceStats / DerivedLocomotion → StatSyncSystem syncs Health.Max / Mana.Max.
When to use
Section titled “When to use”- Implementing or debugging damage, healing, knockback, status effects
- Setting up unit stats (BaseStats → DerivedStatsSystem → combat pipeline)
- Using skill casting, projectiles, AoE, homing, talent trees, synergy
- Working with
CombatAuthoring(canonical unit baker adds 15+ combat components)
Core API
Section titled “Core API”// Damage formula — never inlinefloat dmg = CombatFormulas.ComputeAutoAttackDamage(atk, def, level);float cd = CombatFormulas.EffectiveCooldown(baseCd, haste);uint seed = CombatFormulas.FrameRngSeed(entity, frame);
// Events — per-entity IBufferElementDatabuffer.Add(DamageEvent.Create(source, amount, type));buffer.Add(new HealEvent { Amount = 20 });buffer.Add(new KnockbackEvent { Direction = dir, Force = 5f });
// CC masksif ((state.ActiveCC & CCMasks.MoveBlock) != 0) return; // unit is CC'dExamples
Section titled “Examples”// Custom unit baker (MUST include HitFlashTimer if bypassing CombatAuthoring)this.AddComponent(entity, new HitFlashTimer{ Duration = VisualConstants.HitFlashDuration, OriginalScale = bakedLocalTransform.Scale, // MUST match baked scale});
// Ranged: BOTH Tag AND Config requiredthis.AddComponent<RangedAttackTag>(entity);this.AddComponent(entity, new RangedAttackConfig { ... });Hard rules
Section titled “Hard rules”-
Combat tint/palette constants are stored LINEAR, not authored sRGB.
StatusEffectVisualConstants.*Tint(10 constants) andGameplayConstants.MageAoEColor/TowerAoEColorfeedSpriteColor.Value, which is always linear — seet1k-unity-dots-core-ecs§ “Colour contract” for the full rule andt1k-unity-dots-core-jobs-burst§ “Burst restricts statics” for why they are pinned literals with derivation tests.Two combat specifics worth knowing before you touch them:
StatusEffectTintSystemblends, it does not construct. Itmath.lerps an existingSpriteColor.Valueagainst a raw tint constant through aref, so aSpriteColor.FromGammafactory never runs in that path. Converting only at construction would have made this system newly wrong. The tint table therefore converts at its own definition.CasterAttackSystem,TowerAttackSystemandProjectileCollisionSystemneeded no change — they read constants that are now already linear, so they are correct by inheritance. Each carries an explicit comment saying so; do not “fix” them into a double-convert.
Getting this wrong is invisible to state-side checks: the ECS data reads exactly to spec while the pixel renders wrong. Shipped in The1Studio/unity-dots-library#72.
-
⛔ Every SubScene with stat-bearing units MUST contain a
StatFormulaConfigAuthoring— or every unit’s derived stats (max health, damage, speed) freeze at their baked zero forever. Symptom: the demo appears to spawn nothing, with no console error.Units baked by
StatsAuthoringcarryDOTSCore.BlobConfig.DefId(modern blob path,DefaultFormulaDefId = 0). Resolving it needs aBlobConfigRegistry<StatFormulaBlob>scene singleton, emitted only by aStatFormulaConfigAuthoringGameObject. Without it the failure is silent:no registry→DerivedStatsSystemskips its blob job (m_FormulaBlob.IsCreated == false, no warning) →DerivedResourceStats.MaxHealth(and every other derived stat — PhysAtk, MagAtk, MoveSpeed, …) stays at its baked 0 → the unit sits on the field dealing 0 damage at 0 speed.⚠️ Updated 2026-08-22 (
unity-dots-library@b780a830+@f94069d6):StatSyncSystem.SyncHealthJobno longer runs unconditionally — it now guardsif (resource.MaxHealth <= 0f) return;, treating an exact0as “never derived this session” rather than a real value (DerivedStatsSystem’s clamp always floors a genuinely-derivedMaxHealthto>= 1, so0is unambiguous). An unresolved unit therefore no longer getsHealthstomped to0/0and killed byDeathSystem— it idles instead of dying.DirtyTagClearSystemwas fixed in the same session to match: it now only clearsDirtyTagonce derivation actually succeeded (sameMaxHealth <= 0gate), so a registry that resolves LATE (e.g. SubScene streaming latency) keeps the unit retrying every frame instead of getting permanently frozen the instant a clear pass ran before the registry existed. Full pattern write-up:t1k-unity-dots-core-ecs/references/dirty-tag-guide.md§ Gotchas #4.Two traps remain even with the fix: the authored
Health(e.g. 300) is now preserved rather than overwritten, so “the unit looks alive” proves nothing about whether it can actually fight or move; and the legacy path cannot cover for the missing registry, becauseDerivedStatsJobrequiresin StatFormulaConfig, which blob-path units deliberately lack.Wire it via the library helper — never hand-roll per demo:
SceneSetupUtility.EnsureStatFormulaConfig(subScene, ".../Generated/StatFormulaConfig.asset");Guard:
StatFormulaRegistryGuardSystem(dots-core) logs one console error naming the missing singleton + affected entity count. Audit withgrep -c StatFormulaConfig <SubScene>.unity—0means broken. -
Ranged: BOTH
RangedAttackTagANDRangedAttackConfigrequired.AutoAttackSystemexcludesRangedAttackTag— adding onlyRangedAttackConfigsilently falls back to melee. -
RangedAttackSystemis no-op withoutProjectileRegistryTagsingleton +TeamProjectilePrefabbuffer. Every team needs its own entry; missing-team archers fire 0 projectiles. (Wave-4 rename: wasArrowRegistryTag/TeamArrowPrefab— old names kept as[Obsolete]/[MovedFrom]shims for un-migrated demos.) -
RangedAttackSystem.LookRotationSafemakes 2D projectile quads invisible in sideview — normal points along flight direction (perpendicular to sideview camera). Fix: add a[UpdateAfter(ParabolicArcSystem), OrderLast]system inSkillsSystemGroupthat overrides rotation toquaternion.identity. -
RangedKitingDistanceMUST be ≤ heroAttackRange— hero parked beyond its own range idles indefinitely. -
ISystemforTalentUnlockSystem→ useSystemBase— Entities 1.4BufferTypeHandletwo-pass invalidation. -
SetComponentEnabledbefore buffer reads invalidatesBufferTypeHandle— complete all buffer reads first. -
Combat reward + structures systems consume the v2
DOTSEconomywallet — NOT the deprecatedDOTSInventory.CurrencyWallet/CurrencyTransaction/CurrencyWalletUtility. Reward systems enqueueDOTSEconomy.WalletTransaction; structures systems read/mutateWalletEntryviaWalletUtility; currency keys are nowDOTSEconomy.CurrencyIdenums, notint. TheWallettag is now REQUIRED on any reward/cost target — missing it meansWalletSystemskips the entity and rewards/costs silently no-op. Full v1→v2 contract detail:references/migration-history.md§ “Combat reward + structures systems”. -
SkillSlotis split intoSkillSlotState(hot) +SkillSlotConfig(cold) — the monolithicSkillSlotbuffer is REMOVED. Query BOTH parallel-indexed buffers (int n = math.min(states.Length, configs.Length)), read from each, write back ONLY State.SkillCooldownSystemqueriesSkillSlotStateONLY. Full field lists + the baker invariant:references/migration-history.md§ “SkillSlot is split”. -
Generic component naming — name the ROLE, not the instance. (RESOLVED in Wave-4.) The
Arrow*family (ArrowRegistryTag,TeamArrowPrefab,ArrowPrefabAuthoring) andMage*attack family were over-specific concrete-instance names — really “the projectile a ranged attacker fires” and “an AoE caster’s attack” — while the library ALREADY had genericProjectileData/ProjectileCollisionSystem. Wave-4 (lib v3 post-ship) renamed them to the generic ROLE:Arrow*→Projectile*,Mage*→Caster*, with[MovedFrom]/[Obsolete]back-compat shims (see combat-rpgcombat-v5-migration.md§ “Wave-4 Neutrality Renames (genre-neutral type names)”). The principle still holds for all NEW code: name the generic role (Projectile,Caster,Agent), never one concrete instance (Arrow,Mage,Sword) — a concrete instance belongs in an enum value or demo content. SSOT:rules/library-quality-mandate-unity.md§ “Naming charter”. -
DamageBucketAggregationSystemformula is(flatBucket + percentAddBucket) * percentMulProduct, withpercentMuldefaulting to1.0— NOTflat*(1+add)*mul. These buckets are percentage bonuses, not stats scaled from a base, so a lone+30%PercentAdd buff must yield(0 + 0.30) * 1.0 = 0.30(30%). The oldflat*(1+add)*mulshape multiplied a zeroflatbase and zeroed out every pure-percent buff (PercentAdd-only modifiers silently did nothing). Each bucket (DamagePct,RangedDamagePct,MeleeDamagePct,SkillDamagePct) is clamped toCombatConstants.DamagePercentBucketCap(180%);DefensePctis a 0..1 fraction clamped tighter. Each entity writes only its own bucket component — parallel-safe. -
The stat dirty flag is
DOTSCore.DirtyTag, NOT a per-packageStatsDirtyTag.DOTSCore.StatsDirtyTagis now[Obsolete](a separate, back-compat ECS type scheduled for removal); the canonical enableable flag every package shares isDOTSCore.DirtyTag. The stat-recompute loop is one SSOT chain — ALL of: the baker (bakes the flag enabled for the first-frame pass), the consumer (DerivedStatsSystem— recomputes it, does NOT itself disable the flag), the clear system (DirtyTagClearSystem,OrderLast— disables the flag, and only after a successful recalc), AND every producer that mutates aStatModifierbuffer must set/read the SAMEDOTSCore.DirtyTag. Indots-combatthe producers arePartyBuffSystem,SynergyResolutionSystem,DamageBucketAggregationSystem,StageCurveSystem,TalentUnlockSystem— each callsSetComponentEnabled<DirtyTag>(entity, true)after applying its modifier. A producer that forgets to raiseDirtyTagcauses a silent stat-miss: the recompute never triggers, so the buff lands in the buffer but never reachesDerivedCombatStats. When adding a new modifier-writing system, raisingDirtyTagis part of the contract, not an afterthought.