Damage Everything
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 43 of 50.
Challenge
MediumNow the fight goes both ways. Keep everything from the earlier lessons. The enemies are not tagged any more: the swing finds what it can hurt through an interface instead, and the enemies hurt the hero through the same one.
IDamageabledeclares one method,void TakeDamage(int amount);.Enemyimplements it. It getshealth,damageandattackEvery, set in the Inspector (a grunt has 2, 1 and 1; the dasher 1, 2 and 1).TakeDamagetakesamountoffhealthand destroys the enemy at 0 or below. InStart, keep the hero'sIDamageableas well. Every frame, when the hero is within 1.2 units, call itsTakeDamage(damage), at most once everyattackEveryseconds.Heroimplements it, withswingDamage(1),maxHealth(5) andsafeTime(1) set in the Inspector, and ahealththat starts atmaxHealthinAwake. A hit takesamountoff, logs the health asHero HP: 4, and keeps the hero safe from further hits forsafeTimeseconds. At 0 health, logThe hero fallsand turn the Hero script off (enabled = false). A fallen hero ignores hits.- The swing no longer tests tags or destroys anything: it calls
TakeDamage(swingDamage)on everything in reach and in front that has anIDamageable.
Press Play and fight, then Check.
Try it yourself
// A later lesson fills this in: anything that can be hurt.
public interface IDamageable
{
}
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types