Health and Damage
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 55 of 71.
Damage takes two scripts. A Health script sits on everything that can be hurt and owns its hit points, and whatever does the hurting finds that script and calls a method on it. Here is the Health of a crate that breaks after three hits, and spikes that hurt whatever lands on them:
public class Health : MonoBehaviour
{
[SerializeField] private int hp = 3;
public void TakeDamage(int amount)
{
hp -= amount;
if (hp <= 0)
{
Destroy(gameObject);
}
}
}public class Spikes : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
Health health = collision.gameObject.GetComponent<Health>();
if (health != null)
{
health.TakeDamage(1);
}
}
}TakeDamage is public, so other scripts can call it, and it is the only code that changes hp. Spikes, bullets and lava all call the same method, and the Health script alone decides what 0 means: destroy the crate, end the game or play a death animation. Each script lives in its own file, named after its class.
GetComponent<Health>() returns null for things that have no Health, such as the floor, so the spikes check before calling. TryGetComponent(out Health health) does the lookup and the check in one call: it returns true and fills in health only when there is one.
Challenge
MediumMake the hits count. Bullet is ready and calls TakeDamage(2) on what it hits.
- In
Health, fill inTakeDamage(int amount): takeMathf.Max(amount - armor, 1)offhp. - Log
name + " hp: " + hp, for exampleDummy hp: 2. - When
hp <= 0, callDestroy(gameObject);.
Press Play and shoot the dummy twice: it logs Dummy hp: 2, then vanishes. Then Check.
Try it yourself
using UnityEngine;
public class Health : MonoBehaviour
{
[SerializeField] private int hp = 4;
[SerializeField] private int armor = 0;
public void TakeDamage(int amount)
{
// lose amount minus armor (at least 1), log what is left, destroy at 0
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall3Triggers
Trigger CollidersOnTriggerEnterPickupsCrates Keep the RestKill ZonesEnter and ExitRecap: Key and Door6Raycasts
Physics.RaycastRaycastHitGround Check with a RayLayers and LayerMaskLine of SightOverlapSphere and SphereCastRecap: Laser Tripwire9Enemies
Chase the PlayerChase in RangePatrol and ChaseHealth and DamageBullets That HitKnockbackRecap: Guard DogPractice on your own: Unity playground