Healthbar Code Snippet


Just about every game has some sort of health bar, magic bar or a stamina range with a minimum / maximum value. So I wanted to share how I code up these types of stat ranges in all my games.

The class is called StatRange – no surprise – and it really only has three properties value, min and max but the usefulness comes in with all the helper methods available.

This is how it’s used:

// inside a monobehaviour or where ever
StatRange health = new StatRange();

health.min = 0; // default is zero
health.max = 100;

health.Fill(); // health.value == max
health.value; // 100

// player took damage
health.value -= 10;
health.Clamp(); // keep value within bounds
// OR
health.Minus(10); // 90

// check player is dead
health.IsEmpty; // false

// check at full health
health.IsFull; // false

// easily display health in image / slider in Unity
slider.value = health.Percent; // returns 0 - 1 value
image.fillAmount = health.Percent;

// leveled up, increase max health and clamp
health.max += 10;
health.Clamp();

This is not only limited to health bars, it could be used for anything like it.

magic = new StatRange(0, 50); // init range with 0 - 50
magic.Fill();
magic.IsFull; // true

magic.Minus(10); // casted spell

// remove all mana
magic.Empty(); // 0

stamina = new StatRange(0, 10); // 0 - 10

stamina.Add(1); // add 1 stamina over time
if (stamina.IsFull) {
  // can use run ability
}

Let me know if you found this snippet helpful.

Download source code: StatRange.cs

Related Posts

Simple Explanation of the Pinyin Sounds

Failed Attempt at Creating a Video Search Engine

Test Your Chinese Using This Quiz

Using Sidekiq Iteration and Unique Jobs

Using Radicale with Gnome Calendar

Why I Regret Switching from Jekyll to Middleman for My Blog

Pick Random Item Based on Probability

Quickest Way to Incorporate in Ontario

Creating Chinese Study Decks

Generating Better Random Numbers