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

Migration Approaches from On-Premises to Cloud Environment

Thinking of learning to code? That’s the easy bit. Here’s how to tackle the hard parts.

Transforming developer from commodity to premium — A tale of Microservices

Emulating Azure Storage with Azurite

What Are The Must-Know Unix and Git Commands

Moving Agents on NavMesh with Unity 2021

Principles of Lean Software Development

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

My journey becoming a Unity game developer: Make a game look beautiful-Creating Columns pt.1

Importing Character Models and Animations from Mixamo into Unity

Script Communication in Unity Using GetComponent<>

How to Install the Universal Render Pipeline