How to instantiate a class on every gameObject?

So I want to create an attack Script that removes health, when something is inside of it.
This is the attack-trigger:

void OnTriggerStay(Collider collider)
    {

        if (collider.gameObject.tag == "Enemy")
        {
            var ph = collider.gameObject.GetComponentInParent<PlayerHealth>();
            ph.ModifyHealth(-1);
        }
    }

and this is the Health script attached to the triggered object:

public class PlayerHealth : MonoBehaviour
{
    [SerializeField] static int maxHealth = 100;
    [SerializeField] float refillRepeatRate = 0.2f;

    public int currentHealth;
    public static event Action<float> OnHealthPercentChange;

    void Awake()
    {
        currentHealth = maxHealth;
    }

    public void ModifyHealth(int amount)
    {
        if (currentHealth <= 0) return;
        currentHealth += amount;
        float currentHealthPct = (float)currentHealth / (float)maxHealth;
        OnHealthPercentChange(currentHealthPct);
}

Originally I thought that every adding a script to a gamObject automatically instantiates the class and by using GetCompponent you could access the instance. But this is not the case. Instead the health gets removed globally on all gameObjects like it would be a static.

Would be making the HealthScript a ScriptableObject and then using “new HealthScript” in a different script attached to the gameObject the ideal way to do this? I watched this Video (

) and he directly attached it to the gameObject so I thought it was the “correct” way.

Is there a reason that your OnHealthPercentageChange event is static? That’s why it’s acting like it’s static, because it is!

This is the case. I’m not sure where you’re going wrong, but the code you’ve posted should not be affecting all instances of PlayerHealth.currentHealth.

Oh I missed this. That makes sense! i originally did this so I could update the HealtBar:

public class HealthBar : MonoBehaviour
{
    [SerializeField] private Image foregroundImage;

    void Awake()
    {
        PlayerHealth.OnHealthPercentChange += HandleHealthChanged;
    }

    private void HandleHealthChanged(float percent)
    {
        foregroundImage.fillAmount = percent; //Actually resizes the image
    }

}

But if I remove static and use GetComponentinParent().OnHealthPercentChange I get Null refeerence Exception (Line 19) in my ModifyHealth Method stating that it’s not set to an instance of an Object