Hi, I’m relatively new to Unreal Engine, and was just wondering how I might get a function to trigger an event instead of an event triggering a function. As far as I understand it seems that AddDynamic is used to do the former of those two and not the latter.
In Unreal Engine, events are called delegates.
First declare your delegate in the header file:
// This delegate takes no parameters
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FYourInputEvent);
Create an instance of the delegate in your header file:
FYourInputEvent onInteractInput;
In your cpp code somewhere, broadcast the delegate (ie. fire the event):
onInteractInput.Broadcast();
Somewhere else in your code, subscribe to the delegate to listen for when it is broadcast:
onInteractInput.AddDynamic(this, &AYourClass::YourCoolFunction);
Just one last thing, when I use AddDynamic in this instance it’s giving me an error saying: “no instance of overloaded function “UHealthClass::FDamageTaken::__Internal_AddDynamic” Matches the argument list types” there is a bit more, but I imagine the issue is probably clear to someone familiar with this pretty fast.
cpp:
OnDamage.AddDynamic(this, &UHealthClass::TakeDamage);
void UHealthClass::TakeDamage(AActor* DamageActor, float Damage, const class UDamageType* DamageType, AActor* DamageCauser)
{
if (Damage <= 0)
{
return;
}
else
{
CurrentHealth = FMath::Clamp(CurrentHealth - Damage, 0.0f, DefaultHealth);
CurrentHealth -= 0.1;
}
OnDamage.Broadcast();
}
.h:
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FDamageTaken);
FDamageTaken OnDamage;
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FDamageTaken);
The above is a delegate for a function that take no arguments.
Your TakeDamage
function expects 4 arguments, so the function signatures don’t match.
There are two ways you can fix this. Either simplify your TakeDamage
function so that it takes no arguments, or declare the FDamageTaken
delegate to use 4 parameters.
This is how you would do it for 4 parameters:
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FDamageTaken, AActor*, DamageActor, float, Damage, UDamageType*, DamageType, AActor*, DamageCauser);
Note that in this case, when broadcasting, you would need to fill in the parameters now:
OnDamage.Broadcast(someActor, 5.f, someType, causer);
I would recommend making your life simpler and just pass a single class or struct instead of 4 parameters with DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam
Thank you! This was very helpful!