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
Healthand aHitbox
๐ช 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
| Field | What it does | Set it to |
|---|---|---|
| Damage Points | Amount of health to change | Your attack’s damage, always positive |
| Hit Point | Where the hit landed | hit.point or the contact point |
| Hit Normal | Surface normal at the hit | hit.normal or the contact normal |
| Instigator | The object that caused the change | The 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
Hitboxover callingHealth.Hurtdirectly, 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.