Deal Damage From Your Scripts

Deal Damage From Your Scripts

๐ŸŽฏ Goal

Hurt or heal anything with a hitbox from your own attacks.

๐Ÿงฐ What You Need

  • Your attack script
  • A target with Health and a Hitbox

๐Ÿชœ Steps

Find the Hitbox

Get the Hitbox from the collider your attack hit, from a raycast, a collision or an overlap.

if (Physics.Raycast(ray, out RaycastHit hit, range) &&
    hit.collider.TryGetComponent(out Hitbox hitbox))
{
    // hit something that can take damage
}

Fill a DamageData

Describe the hit: the amount, where it landed, the surface normal and who caused it.

var damage = new DamageData
{
    damagePoints = 25,
    hitPoint = hit.point,
    hitNormal = hit.normal,
    instigator = gameObject,
};

Call Hurt

Call hitbox.Hurt(damage). The hitbox applies its multiplier, then the Health runs its modifiers, such as Invincibility, and applies what’s left. The hitbox’s On Hit fires after.

Heal

To heal, call Heal on the Health itself. Healing skips modifiers and stops at the maximum, and it returns how much was actually restored.

Health health = target.GetComponentInParent<Health>();
health.Heal(new DamageData { damagePoints = 25, instigator = gameObject });

๐Ÿ“ DamageData Fields

FieldWhat it doesSet it to
Damage PointsAmount of health to changeYour attack’s damage, always positive
Hit PointWhere the hit landedhit.point or the contact point
Hit NormalSurface normal at the hithit.normal or the contact normal
InstigatorThe object that caused the changeThe shooter, for score and kill credit

๐Ÿงช Example

DSProjectile in the Duck Shooter examples is the smallest attack. On a collision, it looks for a Hitbox on the collider, fills a DamageData from the first contact with its owner as the instigator, calls Hurt, then destroys itself:

private void OnCollisionEnter(Collision collision)
{
    if (collision.collider.TryGetComponent(out Hitbox hitbox))
    {
        ContactPoint contact = collision.GetContact(0);
        hitbox.Hurt(new DamageData
        {
            damagePoints = _damage,
            hitPoint = contact.point,
            hitNormal = contact.normal,
            instigator = owner,
        });
    }
    OnImpact.Invoke();
    Destroy(gameObject);
}

๐Ÿ’ก Tips

  • Prefer hurting a Hitbox over calling Health.Hurt directly, so multipliers and On Hit apply.
  • Health.AffectHealth(-amount, data) skips modifiers. Use it for damage that should ignore invincibility, such as falling out of the level.
  • For explosions, an overlap can return several hitboxes of the same target. Keep a set of the Healths you already hurt if each target should only be hit once.
  • The Modular Weapon System’s barrels and ammo already damage hitboxes this way, so weapons from that package work with no extra code.

๐Ÿ”— Related