IDamagable Interface in Unity

  • This code is difficult, if not impossible to maintain or upgrade in a very high scale, because you’ll need to the same last 3 lines of code for each enemy type, and they could be dozens or hundreds of them
  • the ApplyDamage() method must be public to be accessed, and it’s a non-recommended practice due to possible unwanted access from other scripts
  • Create a new script, call it IDamageable
  • declare as an interface instead of a class :
    public interface IDamageable
  • //1 and //2 do the same
  • public void Damage() will be implemented (executed) in the same way for all the enemies. If you want to customize it in any of them, you’ll need to add the virtual keyword. This will be useful, for example, when adding animations or particle systems.
  • Health and health values behave differently.
    In the code above, Health will take the health value as a starting value, and Damage() will decrease Health, but health will remain the same.
    If you want to update the health value, you’ll need to add
    health = Health in Damage() in Enemy script.
    It depends on the required implementation.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

5 Advanced Code snippets for your Python programs

How I got my (functional) team to collaborate with many Scrum teams

Breaking Dependencies and Refactoring Part 1

Be professional developer: Part 1

Six Lessons From Scratching

How to Setup & Run a Utility Node

How to Host your Unity Game Online

Learning Elasticsearch Basic Easily

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hernando Nieto Jaramillo

Hernando Nieto Jaramillo

Unity developer

More from Medium

Ease Of Building UI Elements In Unity

Upgrading A Unity Project To The Universal Render Pipeline (URP)

Day 97: Game Assets via Filebase

A Modular Power up System In Unity