Class EntityHealth
- Namespace
- ElectricDrill.AstraHealth.Core
- Assembly
- com.electricdrill.astra-health.Runtime.dll
Manages the health, damage, and healing mechanics for an entity. Handles damage calculation, health regeneration, barriers (temporary HP), and death events.
[RequireComponent(typeof(EntityCore))]
public class EntityHealth : MonoBehaviour, IDamageable, IHealable, IResurrectable, IHasEntity, IBarrierContainer, IEventRegistrar
- Inheritance
-
objectEntityHealth
- Implements
-
IHasEntityIEventRegistrar
Remarks
Internal serialized fields — access contract
Several fields in this class are marked [SerializeField, HideInInspector] internal.
This combination encodes a deliberate three-way contract:
[SerializeField]— Unity persists the value to the scene/prefab asset.[HideInInspector]— the default Inspector hides the field; the customEntityHealthEditorowns the entire UI and reads/writes values exclusively viaSerializedProperty(e.g.,FindProperty("_hp")).internal— accessible to package-internal helpers (ElectricDrill.AstraHealth.Core.MaxHpCalculator,LifestealResolver, etc.) that live in the same Runtime assembly, and to test assemblies declared inAssemblyInfo.csviaInternalsVisibleTo.
EntityHealth or its designated
package-internal helpers is a bug. The only legitimate write paths are:
- Unity deserialization (scene/prefab load).
EntityHealthEditorviaSerializedProperty(Inspector).- Package-internal helpers (
MaxHpCalculator, etc.) during runtime logic. - Test setup code in the sibling test assembly.
Properties
Barrier
Gets the current barrier points (temporary HP) of the entity.
public long Barrier { get; }
Property Value
- long
Class
Gets or sets the EntityClass component associated with this entity.
public EntityClass Class { get; set; }
Property Value
- EntityClass
Entity
The primary ElectricDrill.AstraRpgFramework.EntityCore associated with this object. For entity components this is the owning entity; for context payloads this is the primary affected subject (e.g. the event target).
public EntityCore Entity { get; }
Property Value
- EntityCore
EntityAttributes
Gets or sets the EntityAttributes component associated with this entity.
public EntityAttributes EntityAttributes { get; set; }
Property Value
- EntityAttributes
EntityCore
Gets or sets the EntityCore component associated with this entity.
public EntityCore EntityCore { get; set; }
Property Value
- EntityCore
EntityStats
Gets or sets the EntityStats component associated with this entity.
public virtual EntityStats EntityStats { get; set; }
Property Value
- EntityStats
HealthCanBeNegative
Gets or sets whether the entity's health can go below zero. When set to true, a death threshold must be defined.
public bool HealthCanBeNegative { get; set; }
Property Value
- bool
Hp
Gets the current health points of the entity.
public long Hp { get; }
Property Value
- long
IsImmune
Gets or sets whether the entity is immune to all damage.
public bool IsImmune { get; set; }
Property Value
- bool
MaxHp
Gets the maximum health points of the entity.
public long MaxHp { get; }
Property Value
- long
OverrideOnDeathGameAction
Gets or sets the override ElectricDrill.AstraRpgFramework.GameActions.GameAction<TContext> for handling entity death. This game action takes precedence over the default game action defined in the config. If null, the default game action from the AstraHealthConfigSO configuration will be used.
public GameAction<IHasEntity> OverrideOnDeathGameAction { get; set; }
Property Value
- GameAction<IHasEntity>
OverrideOnResurrectionGameAction
Gets or sets the override ElectricDrill.AstraRpgFramework.GameActions.GameAction<TContext> for handling entity resurrection. This game action takes precedence over the default game action defined in the config. If null, the default game action from the AstraHealthConfigSO configuration will be used.
public GameAction<IHasEntity> OverrideOnResurrectionGameAction { get; set; }
Property Value
- GameAction<IHasEntity>
Methods
AddBarrier(long)
Adds the specified amount to the entity's barrier pool.
public void AddBarrier(long amount)
Parameters
amountlongPositive amount to add.
AddMaxHpFlatModifier(long, HpBehaviourOnMaxHpIncrease, HpBehaviourOnMaxHpDecrease)
Adds a flat modifier to the entity's maximum health.
public void AddMaxHpFlatModifier(long amount, EntityHealth.HpBehaviourOnMaxHpIncrease onMaxHpIncrease = HpBehaviourOnMaxHpIncrease.None, EntityHealth.HpBehaviourOnMaxHpDecrease onMaxHpDecrease = HpBehaviourOnMaxHpDecrease.RemoveHealthUpToMaxHp)
Parameters
amountlongThe amount to add to the flat modifier. Can be negative.
onMaxHpIncreaseEntityHealth.HpBehaviourOnMaxHpIncreaseBehavior to apply when max HP increases.
onMaxHpDecreaseEntityHealth.HpBehaviourOnMaxHpDecreaseBehavior to apply when max HP decreases.
AddMaxHpPercentageModifier(Percentage, HpBehaviourOnMaxHpIncrease, HpBehaviourOnMaxHpDecrease)
Adds a percentage modifier to the entity's maximum health.
public void AddMaxHpPercentageModifier(Percentage amount, EntityHealth.HpBehaviourOnMaxHpIncrease onMaxHpIncrease = HpBehaviourOnMaxHpIncrease.None, EntityHealth.HpBehaviourOnMaxHpDecrease onMaxHpDecrease = HpBehaviourOnMaxHpDecrease.RemoveHealthUpToMaxHp)
Parameters
amountPercentageThe percentage to add to the modifier.
onMaxHpIncreaseEntityHealth.HpBehaviourOnMaxHpIncreaseBehavior to apply when max HP increases.
onMaxHpDecreaseEntityHealth.HpBehaviourOnMaxHpDecreaseBehavior to apply when max HP decreases.
AddMaxHpScaling(StatsScalingComponentSO, HpBehaviourOnMaxHpIncrease, HpBehaviourOnMaxHpDecrease)
Adds a stats-based scaling component that dynamically affects maximum health. Subscribes to stat changes if this is the first scaling added.
public void AddMaxHpScaling(StatsScalingComponentSO scaling, EntityHealth.HpBehaviourOnMaxHpIncrease onMaxHpIncrease = HpBehaviourOnMaxHpIncrease.None, EntityHealth.HpBehaviourOnMaxHpDecrease onMaxHpDecrease = HpBehaviourOnMaxHpDecrease.RemoveHealthUpToMaxHp)
Parameters
scalingStatsScalingComponentSOThe scaling component to add.
onMaxHpIncreaseEntityHealth.HpBehaviourOnMaxHpIncreaseBehavior to apply when max HP increases because of the scaling.
onMaxHpDecreaseEntityHealth.HpBehaviourOnMaxHpDecreaseBehavior to apply when max HP decreases because of the scaling.
ClearMaxHpScalings(HpBehaviourOnMaxHpIncrease, HpBehaviourOnMaxHpDecrease)
Removes all stats-based scaling components from maximum health calculations.
public void ClearMaxHpScalings(EntityHealth.HpBehaviourOnMaxHpIncrease onMaxHpIncrease = HpBehaviourOnMaxHpIncrease.None, EntityHealth.HpBehaviourOnMaxHpDecrease onMaxHpDecrease = HpBehaviourOnMaxHpDecrease.RemoveHealthUpToMaxHp)
Parameters
onMaxHpIncreaseEntityHealth.HpBehaviourOnMaxHpIncreaseonMaxHpDecreaseEntityHealth.HpBehaviourOnMaxHpDecrease
GetHpPortion(double)
Returns the amount of current HP represented by the given portion.
public long GetHpPortion(double portion)
Parameters
portiondoubleThe portion of current HP (e.g., 0.2 means 20%).
Returns
- long
GetMaxHpPortion(double)
Returns the amount of max HP represented by the given portion.
public long GetMaxHpPortion(double portion)
Parameters
portiondoubleThe portion of max HP (e.g., 0.2 means 20%).
Returns
- long
GetMissingHpPortion(double)
Returns the amount of missing HP represented by the given portion.
public long GetMissingHpPortion(double portion)
Parameters
portiondoubleThe portion of missing HP (e.g., 0.2 means 20%).
Returns
- long
Heal(PreHealContext)
Heals the entity by the specified amount, applying critical multipliers and heal modifiers. The actual health gained may be less than the heal amount if the entity is at or near maximum health. Throws DeadEntityException if the entity is dead.
Heal Calculation:
- Apply critical multiplier if the heal is flagged as critical.
- Apply generic heal modifier stat (if configured).
- Apply heal source-specific modifier stat (if configured and heal source matches).
- Add the final calculated heal amount to current health (capped at max HP).
Heal modifiers stack additively (e.g., +25% generic heal + +10% source-specific = +35% total).
public ReceivedHealContext Heal(PreHealContext context)
Parameters
contextPreHealContextThe pre-heal information including amount, source, and healer.
Returns
- ReceivedHealContext
Information about the heal received including the actual health gained.
Exceptions
- DeadEntityException
Thrown when attempting to heal a dead entity.
Heal(PreHealContext, bool)
Heals the entity by the specified amount, applying critical multipliers and heal modifiers. The actual health gained may be less than the heal amount if the entity is at or near maximum health. Throws DeadEntityException if the entity is dead.
Event behaviour:
-
When
suppressHealEventsistrue, the pre-heal event (GlobalPreHealInfoEvent) and the entity-healed event (GlobalEntityHealedEvent) are not raised. -
The HP-change events (
GlobalHealthChangedEventandGlobalHealthRatioChangedEvent) are always raised when health actually changes, regardless of this flag. UI components tracking entity health depend on these events to stay in sync.
Use suppressHealEvents: true when the heal is an implementation detail (e.g. passive
regeneration, lifesteal) and raising the full heal event pipeline would cause unwanted
side-effects or noise.
public ReceivedHealContext Heal(PreHealContext context, bool suppressHealEvents)
Parameters
contextPreHealContextThe pre-heal information including amount, source, and healer.
suppressHealEventsboolWhen
true, suppresses the pre-heal and entity-healed event channels. HP-change channels are always raised.
Returns
- ReceivedHealContext
Information about the heal received including the actual health gained.
Exceptions
- DeadEntityException
Thrown when attempting to heal a dead entity.
IsAlive()
Checks if the entity's current health is above the death threshold.
public bool IsAlive()
Returns
- bool
true if current health is > death threshold, false otherwise
IsDead()
Checks if the entity's current health is at or below the death threshold. Returns the cached death state for performance.
public bool IsDead()
Returns
- bool
true if current health is <= death threshold, false otherwise
ManualHealthRegenerationTick()
Method to be called to trigger manual health regeneration (e.g., if you are using a turn-based system, call this method at the start/end of each turn).
public void ManualHealthRegenerationTick()
RemoveBarrier(long)
Removes the specified amount from the entity's barrier pool, flooring at zero.
public void RemoveBarrier(long amount)
Parameters
amountlongPositive amount to consume.
RemoveMaxHpScaling(StatsScalingComponentSO, HpBehaviourOnMaxHpIncrease, HpBehaviourOnMaxHpDecrease)
Removes a previously added stats-based scaling component from maximum health calculations. Unsubscribes from stat changes if no scalings remain.
public void RemoveMaxHpScaling(StatsScalingComponentSO scaling, EntityHealth.HpBehaviourOnMaxHpIncrease onMaxHpIncrease = HpBehaviourOnMaxHpIncrease.None, EntityHealth.HpBehaviourOnMaxHpDecrease onMaxHpDecrease = HpBehaviourOnMaxHpDecrease.RemoveHealthUpToMaxHp)
Parameters
scalingStatsScalingComponentSOThe scaling component to remove.
onMaxHpIncreaseEntityHealth.HpBehaviourOnMaxHpIncreaseBehavior to apply when max HP increases because of the scaling removal.
onMaxHpDecreaseEntityHealth.HpBehaviourOnMaxHpDecreaseBehavior to apply when max HP decreases because of the scaling removal.
Resurrect(PreHealContext)
Resurrects the entity using the provided PreHealContext, routing through Heal(PreHealContext)
so that all heal modifiers (generic and HealSourceSO-specific) are applied.
The Amount is the base heal amount before modifiers; the actual HP
after resurrection may differ.
If the modifiers reduce the effective HP to or below the death threshold, a fallback of
deathThreshold + 1 is applied to guarantee the entity is always resurrected alive.
Throws System.InvalidOperationException if the entity is already alive.
public void Resurrect(PreHealContext preHealContext)
Parameters
preHealContextPreHealContextThe pre-heal context describing amount, source and healer for the resurrection heal.
Exceptions
- InvalidOperationException
Thrown when attempting to resurrect an entity that is already alive.
Resurrect(Percentage)
Convenience overload. Resurrects the entity with a percentage of its maximum HP. Builds a PreHealContext using the DefaultResurrectionSource and no healer entity. For full control over source and healer use Resurrect(PreHealContext). Throws System.InvalidOperationException if the entity is already alive.
public void Resurrect(Percentage withHpPercent)
Parameters
withHpPercentPercentageThe percentage of maximum HP to restore on resurrection (before heal modifiers). Expected range is [0, 100] (i.e. 0% to 100%). Values outside this range trigger a UnityEngine.Debug.LogWarning(object) and are clamped to [0, 100] before use.
Exceptions
- InvalidOperationException
Thrown when attempting to resurrect an entity that is already alive.
Resurrect(long)
Convenience overload. Resurrects the entity with a base amount of HP. Builds a PreHealContext using the DefaultResurrectionSource and no healer entity. For full control over source and healer use Resurrect(PreHealContext). Throws System.InvalidOperationException if the entity is already alive.
public void Resurrect(long withHp)
Parameters
withHplongThe base HP amount to restore on resurrection (before heal modifiers).
Exceptions
- InvalidOperationException
Thrown when attempting to resurrect an entity that is already alive.
SetHpToMax()
Sets the entity's current health to its maximum health value. Throws DeadEntityException if the entity is dead.
public void SetHpToMax()
Exceptions
- DeadEntityException
Thrown when attempting to set HP to max on a dead entity.
SetupMaxHp(HpBehaviourOnMaxHpIncrease, HpBehaviourOnMaxHpDecrease)
Recalculates and updates the entity's maximum health based on base value, modifiers, and scaling. Raises the max health changed event if the value differs from the previous maximum. If the entity is dead, only recalculates max HP and raises events without adjusting current HP.
public void SetupMaxHp(EntityHealth.HpBehaviourOnMaxHpIncrease onMaxHpIncrease, EntityHealth.HpBehaviourOnMaxHpDecrease onMaxHpDecrease = HpBehaviourOnMaxHpDecrease.RemoveHealthUpToMaxHp)
Parameters
onMaxHpIncreaseEntityHealth.HpBehaviourOnMaxHpIncreaseBehavior to apply when max HP increases.
onMaxHpDecreaseEntityHealth.HpBehaviourOnMaxHpDecreaseBehavior to apply when max HP decreases.
Subscribe<TEvent>(TEvent)
Registers gameEvent on the channel matching TEvent.
public void Subscribe<TEvent>(TEvent gameEvent) where TEvent : ScriptableObject
Parameters
gameEventTEvent
Type Parameters
TEvent
Exceptions
- ArgumentException
Thrown when no channel is registered for
TEvent.
TakeDamage(PreDamageContext)
Applies damage to the entity through the damage calculation pipeline. This is the primary method for dealing damage in the Astra Health system.
Execution Order:
- Death State Check: If the entity is already dead, the damage is marked as prevented with EntityDead reason and returned immediately. Dead entities cannot take damage.
- Pre-Damage Event: Raises the PreDamageGameEvent to notify listeners of incoming damage. This allows systems to react before any damage calculations occur.
- DamageInfo Creation: Converts the PreDamageContext into a DamageInfo object that will track the damage through the calculation pipeline.
- Immunity Check: If the entity is immune (IsImmune is true), the damage is marked as prevented with EntityImmune reason. This happens before the pipeline to short-circuit processing.
- Damage Calculation Pipeline: If damage is not already prevented, the configured
DamageCalculationStrategy processes the damage. The pipeline can apply:
- Damage mitigation based on defensive stats
- Barrier consumption (temporary HP absorption)
- Critical hit calculations
- General damage and/or damage type and damage source modifiers
- Custom pipeline stages defined in the strategy
- Prevention Check: If the damage was prevented (either by immunity or during the pipeline):
- Creates a DamageResolutionContext.Prevented result with all prevention reasons
- Raises the DamageResolutionGameEvent
- Returns immediately without affecting health
- Health Reduction: If damage was not prevented, the final calculated damage amount is subtracted from the entity's current health via RemoveHealth(). This may trigger the HealthChangedGameEvent.
- Damage Resolution Event: Raises the DamageResolutionGameEvent with the applied damage information. This allows systems to react to successful damage (e.g., lifesteal, on-hit effects).
- Death Check: If the entity's health is now at or below the death threshold:
- Raises the EntityDiedGameEvent with this EntityHealth and the DamageResolutionContext
- Executes the on-death Game Action (either the entity's override or the config default)
- The death strategy handles the actual death behavior (e.g., destroy, return ot the object pool, disable, ragdoll)
- Return: Returns a DamageResolutionContext.Applied result containing all damage information for the caller to process if needed.
Strategy Selection:
The method uses the first available DamageCalculationStrategy in this priority order:- OverrideDamageCalculationStrategy (if set on this EntityHealth)
- CustomDamageCalculationStrategy (if set on this EntityHealth)
- DefaultDamageCalculationStrategy (from the AstraRpgHealthConfig)
public DamageResolutionContext TakeDamage(PreDamageContext preDamage)
Parameters
preDamagePreDamageContextThe pre-damage information including base amount, damage type, dealer entity, and additional context. This is used by the damage calculation pipeline to compute the final damage to apply.
Returns
- DamageResolutionContext
A DamageResolutionContext indicating whether damage was applied or prevented. If prevented, includes the reasons for prevention. If applied, includes the final damage amounts and calculation details.
Unsubscribe<TEvent>(TEvent)
Removes gameEvent from the channel matching TEvent.
public void Unsubscribe<TEvent>(TEvent gameEvent) where TEvent : ScriptableObject
Parameters
gameEventTEvent
Type Parameters
TEvent
Exceptions
- ArgumentException
Thrown when no channel is registered for
TEvent.