2D Mobile: IDamageable Interface

Gabriel Perez
2 min readJan 8, 2022

The IDamageable interface gives common functionality to game objects that can be destroyed. Its implementation holds a health property and a Damage function with a parameter of int amount.

public interface IDamageable
{
int Health { get; set; }
void OnDamage(int amount);
}

I implemented the interface to the player and enemy base class. I can also implement it in other objects when the time comes, such as a breakable wall or box.

With a health property implemented, I can use the Damage function to give the logic for when the player loses health and dies.

public void OnDamage(int amount)
{
health -= amount;
print(“Player is Hit!”);
if(health <= 0)
{
//Game over
print(“Game Over”);
_anim.Death();
}
}

OnDamage() gets called from objects that attack. So in this case, I have an Attack script attached to a game object that acts as the player’s sword. The game object is called Hitbox, and it holds a box collider 2d as well. The box collider is animated to follow the swing of the attack animation. It needs the Attack script so that it can check for an IDamageable component from the collider it hits. It doesn’t care who it hits. It only cares if the game object with the collider it hits has an IDamageable component.

private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log(“Hit: “ + other.gameObject.name);
var hit = other.GetComponent<IDamageable>();
if (hit != null)
{
if (!_onHit)
{
hit.OnDamage(damageAmount);
_onHit = true;
}
StartCoroutine(AttackResetRoutine());
}
}

That is the beauty of interfaces. Use them when there is common functionality for unrelated classes.

Gabriel

--

--

Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.