Delegates in Unreal

Suneet Agrawal
2 min readNov 9, 2024

--

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:

  1. Single-cast Delegates
  2. Multi-cast Delegates
  3. Dynamic Single-cast Delegates
  4. 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

Please continue reading at https://agrawalsuneet.github.io/blogs/delegates-in-unreal/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

No responses yet