Better than paying for health insurance

Component system are a tricky balancing act to perform. Make them too specialized and you’ll bog down your system with an abundance of messages and function overhead. At the same time making them too generalized leaves you with bloated elements that carry unneeded complexity into most of their uses.

Let’s take our health component, it’s on the side of being over specialized; it handles only a few functions and variables. Let’s say we wanted to have armor as well as health? as it stands we’d need to add an entire extra component. This component would need to capture the damage, modify it, then pass the result to the health component. A better option would be to add Armor to the Health component. This modification will give the user a Doom style armor value that can go up and will degrade as damage is taken

using UnityEngine;

public class HealthComponent : MonoBehaviour
{
    [SerializeField]
    private float MaxHealth = 100;

    [SerializeField]
    private float Health = 100;

    [SerializeField]
    private float MaxArmor = 100;

    [SerializeField]
    private float Armor = 0;

    public void ApplyDamage(float Amount)
    {
        if (Armor > 0) {
            Armor -= Amount;
            if (Armor > 0) {
                return;
            }

            Amount = Math.abs(Armor);
            Armor = 0;
        }

        Health -= Amount;
        if (Health <= 0)
        {
            SendMessage(“onDeath”);
        }
    }
}

Here we no longer have to capture, modify, and relay messages. We simply modify the values directly and only have 8 bytes of overhead on entities that use our component. We can also Make an ArmorHealthComponent that extends the HealthComponent and overrides ApplyDamage; best of both worlds.

Keeping in mind the balance between specialization and generalization of your components will help you design a system that won’t have you ripping your hair out. Next time we’ll move on from components and talk about Blueprints and the Unreal environment.