Delegates in Unreal
Delegates in Unreal Engine play an essential role in creating modular, decoupled, and event-driven code. They allow one object to call a function on another object without hard-wiring the dependency between them, which is perfect for implementing event-driven behavior. In Unreal, delegates are especially useful in game development to handle events, respond to actions, or manage callbacks.
This post was originally posted at https://agrawalsuneet.github.io/blogs/delegates-in-unreal/ and later reposted on Medium.
In this blog, we’ll go through the different types of delegates in Unreal Engine, explaining what they are, how they differ, and providing code examples for each type.
What is a Delegate?
A delegate in Unreal is a type-safe callback mechanism that allows one part of code to “delegate” functionality to another. Delegates are powerful tools to manage responses to actions, such as when a player triggers a specific action or when a game object completes an animation or reaches a target location.
In Unreal Engine, there are four main types of delegates:
- Single-cast Delegates
- Multi-cast Delegates
- Dynamic Single-cast Delegates
- Dynamic Multi-cast Delegates
Let’s take a deeper look into each type.
1. Single-cast Delegates
A single-cast delegate is a delegate that can have only one binding at any given time. This is useful for situations where only one object needs to respond to a particular event.
How to Declare and Use Single-cast Delegates
// Declare a Single-cast Delegate
DECLARE_DELEGATE(FOnHealthChanged);
// A class using Single-cast Delegate
class APlayerCharacter : public ACharacter
{
public:
// The single-cast delegate instance
FOnHealthChanged OnHealthChangedDelegate;
void TakeDamage(float DamageAmount)
{
Health -= DamageAmount;
OnHealthChangedDelegate.ExecuteIfBound(); // Trigger the delegate
}
};
Binding and Executing a Single-cast Delegate
APlayerCharacter* Player = GetPlayerCharacter();
Player->OnHealthChangedDelegate.BindLambda([]()
{
UE_LOG(LogTemp, Warning, TEXT("Player's health has changed!"));
});
Player->TakeDamage(50.0f); // This will call the delegate if health changes
2. Multi-cast Delegates
A multi-cast delegate can bind multiple functions to a single event, allowing multiple listeners to respond when the event occurs. Multi-cast delegates are perfect when multiple systems or actors need to respond to the same event, such as a global game event that should notify various UI elements.
How to Declare and Use Multi-cast Delegates