Menu
CoddyTech

Damage Everything

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 43 of 50.

challenge icon

Challenge

Medium

Now 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.

  • IDamageable declares one method, void TakeDamage(int amount);.
  • Enemy implements it. It gets health, damage and attackEvery, set in the Inspector (a grunt has 2, 1 and 1; the dasher 1, 2 and 1). TakeDamage takes amount off health and destroys the enemy at 0 or below. In Start, keep the hero's IDamageable as well. Every frame, when the hero is within 1.2 units, call its TakeDamage(damage), at most once every attackEvery seconds.
  • Hero implements it, with swingDamage (1), maxHealth (5) and safeTime (1) set in the Inspector, and a health that starts at maxHealth in Awake. A hit takes amount off, logs the health as Hero HP: 4, and keeps the hero safe from further hits for safeTime seconds. At 0 health, log The hero falls and 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 an IDamageable.

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