How to notify unknown object of an action?

Hello,

I’m trying to make a generic ‘Hitpoints’ script that can be used on any object that can be damaged. I would like to make it so that when the “currentHitpoints” of the object is at or below zero, it notifies some other object/component that the object is dead. I would like to be able to stick this script on anything from an NPC to a flower vase. This is a simplified version of what I’m going for but don’t know how to fill in UnitDead() function:

public class Hitpoints : MonoBehaviour
{
	public int startingHitpoints;

	private int currentHitpoints;

	void Start()
	{
		currentHitpoints = startingHitpoints;
	}

	void Update()
	{

	}

	public void TakeDamage(int damageVal)
	{
		currentHitpoints -= damageVal;

		if (currentHitpoints <= 0)
		{
			UnitDead();
		}
	}

	private void UnitDead()
	{
		//notify some object/component that hitpoints has reached 0
	}

	public void ResetHitpoints()
	{
		currentHitpoints = startingHitpoints;
	}
}

Is there some generic way to accomplish this? Thank you for the help!

Events are exactly what you are looking for

 public class Hitpoints : MonoBehaviour
 {
     public int startingHitpoints;

     public UnityEngine.Events.UnityEvent OnDeath;
 
     private int currentHitpoints;
 
     void Start()
     {
         currentHitpoints = startingHitpoints;
     }
 
     public void TakeDamage(int damageVal)
     {
         currentHitpoints -= damageVal;
 
         if (currentHitpoints <= 0)
         {
             UnitDead();
         }
     }
 
     private void UnitDead()
     {
         if( OnDeath != null )
              OnDeath.Invoke();
     }
 
     public void ResetHitpoints()
     {
         currentHitpoints = startingHitpoints;
     }
 }

Then, in the inspector, you will see a box like the Button’s onClick. You can add the gameObject and the function you want which will be called when the unit dies.

To do the same by code :

 // Add a function with no argument
 hitPointGameObject.GetComponent<Hitpoints>().OnDeath.AddListener( Foo );

 // Add a function with arguments
 hitPointGameObject.GetComponent<Hitpoints>().OnDeath.AddListener( () =>
 {
      Bar( "John Doe", 0 );
 } );
// ....

 private void Foo()
 {
      Debug.Log("Foo");
 }

 private void Bar( string name, int number )
 {
      Debug.Log( name + " " + number );
 }