Unity Development — Modular Health

In general, when coding the user controlled Player and the computer controlled enemies, they would have very little in common. Sometimes, however, you can still save some time by finding something common and making sure not to code it twice.

In this example, both our Player and the Enemy have health and can have some of that health damaged. To keep up with the principals of object oriented programming, we will have a separate class/script specifically for health and damage that will go on both objects.

Right away we declare a max health, min health, and current health. They are serialized, so that they can be given different values to the different objects. At the beginning for the scene, the current health is set to the max health as well. Now we’ll make a public Damage() function.

Since this function is public, we can call it from anywhere we get a reference to the object and the Health script. The Player has a shooting mechanic with a Raycast. If it hits an Enemy, it can search for the Health script. If it isn’t null, it can perform the Damage function.

The same goes for the Enemy. It has a reference to the player and thus can call on the Health script and Damage() as long as it isn’t null, in a completely separate circumstance.

And that’s really all there is to it. There are other ways to do this. Interfaces is a good example, but that is one for another day.




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

Recommended from Medium

Xero’s OpenAPI story

Factory Method Design Pattern

Displaying Lithology Data Using Python and matplotlib

Well log plot with gamma ray, neutron porosity and bulk density data plotted alongside lithology data.

SQL Injection Attack and it’s prevention

parameter binding

My Azure Certification Timeline : AZ-204

One More Time Codes November

One More Time Codes November

Google Search Hacks — How to Use Google to Your Fullest?

Boostcards — Rethinking Utility in NFT’s

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
Christopher Graf

Christopher Graf

More from Medium

Journal 143 — Unity Project Development, 2.5D Shooter

Command Pattern in Unity

Create a Diablo Style Character Controller in Unity!

Adding Player Audio Effects