Make Actor Component respond to TakeDamage() on parent Actor

So basically what I’m trying to do is to create a single unified ActorComponent that will handle health and damage for any actor it is attached to.

I want to make it so that by simply attaching my component to some Actor, that actor now can have HP and shields and whatever.

However I ran into a problem of understanding here, a bit.

So basically, when something deals damage to my Actor, than on that actory TakeDamage() function is called. I can overload this function on the actor and handle damage there. But I wanted to make it so that as long my ActorComponent is attached to the actor, then whenever actor takes damage from anything - a function on the component is called and handles the situation. Without me having to add any code to the actor itself.

How can I do that?
Someone said that I should use delegates, but I would still need to add a delegate to the actor, so basically the purpose of not having to add any code is defeated.

Thanks in advance for responses.

2 Likes

It is indeed done through delegates.

In YourComponent.h you add a function:

UFUNCTION()
void TakeDamage(AActor* DamagedActor, float Damage, const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageCauser);

Note that it can be called however you want. You obviously implement this function in your .cpp file.
Note also that this call differs slightly from a standard TakeDamage() that you would overload on your actor. It has an additional parameter at the front - AActor DamagedActor*

Also in the initialization block of your .cpp file you write this:

GetOwner()->OnTakeAnyDamage.AddDynamic(this, &UYourComponent::TakeDamage);

This will subscribe your TakeDamage function to an event that occurs on the owner Actor.

1 Like