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

Rockstar Games (Bengaluru) Senior Java Developer Coding Round questions

How to debug your Linux BSP

“I speak English, French, PHP and Javascript, you?”

This is why the HyperLogLog algorithm is my new favorite

Playing the No Internet Dino game just by blinking

Bypassing reCAPTCHA v2

How to Approach Your First Hackathon

Create and Setup Azure VM

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

Creating Elevator in Unity — Part 3: Moving Elevator.

Asset Bundles for Unity

Day 103: Creating A Ledge Grab in Unity Part 1

How to Make the Camera Shake Using Impulse Listener Extensions in Cinemachines Virtual Cameras