TExcelTAD
Home › Unreal Engine 5 with C++ › Delegates

Delegates

A delegate is Unreal's type-safe callback: a variable that holds "call this function on this object". Delegates are how gameplay code announces events (health changed, enemy died, ability ended) without knowing who is listening. That decoupling keeps the UI, audio and achievements out of your gameplay classes.

The four kinds

Declared with Bound functions Blueprint? Use for
DECLARE_DELEGATE_OneParam(FOnPicked, int32) one no a single callback: "call me when the load finishes"
DECLARE_MULTICAST_DELEGATE_OneParam(FOnDied, AActor*) many no C++-only events; fastest
DECLARE_DYNAMIC_DELEGATE_OneParam(FOnDone, bool, bSuccess) one yes, as a parameter Blueprint-callable functions that take a callback
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnHealthChanged, float, NewHealth) many yes (BlueprintAssignable) events designers bind to in Blueprints

Dynamic delegates are reflected: they can be serialized and bound from Blueprints, but they bind by function name, so the target must be a UFUNCTION, and they are slower. Dynamic macros name each parameter (float, NewHealth); the non-dynamic ones only list types. Suffixes go up to _NineParams, and _RetVal variants return a value (single-cast only).

A health component that broadcasts

cpp
// HealthComponent.h
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnHealthChanged, float, NewHealth, float, Delta);
DECLARE_MULTICAST_DELEGATE_OneParam(FOnDiedNative, AActor* /*Killer*/);

UCLASS(ClassGroup = (Arena), meta = (BlueprintSpawnableComponent))
class ARENA_API UHealthComponent : public UActorComponent
{
    GENERATED_BODY()

public:
    UPROPERTY(BlueprintAssignable, Category = "Health")
    FOnHealthChanged OnHealthChanged;            // Blueprints: "Assign On Health Changed"

    FOnDiedNative OnDied;                        // C++ listeners only

    void ApplyDamage(float Amount, AActor* Instigator);

private:
    float Health = 100.f;
};

// HealthComponent.cpp
void UHealthComponent::ApplyDamage(float Amount, AActor* Instigator)
{
    if (Amount <= 0.f || Health <= 0.f) return;
    const float Old = Health;
    Health = FMath::Max(0.f, Health - Amount);
    OnHealthChanged.Broadcast(Health, Health - Old);
    if (Health <= 0.f)
    {
        OnDied.Broadcast(Instigator);
    }
}

Binding and unbinding

cpp
// A widget or another actor listens:
void AArenaScoreKeeper::Watch(UHealthComponent* Health)
{
    Health->OnHealthChanged.AddDynamic(this, &AArenaScoreKeeper::HandleHealthChanged);   // must be a UFUNCTION
    DiedHandle = Health->OnDied.AddUObject(this, &AArenaScoreKeeper::HandleDied);
    Health->OnDied.AddLambda([](AActor* Killer) { UE_LOG(LogTemp, Log, TEXT("died")); }); // careful: no lifetime check
    Health->OnDied.AddWeakLambda(this, [this](AActor* Killer) { ++Deaths; });            // skipped if `this` is gone
}

void AArenaScoreKeeper::EndPlay(const EEndPlayReason::Type Reason)
{
    // Watched: UPROPERTY() TObjectPtr<UHealthComponent>, DiedHandle: FDelegateHandle
    if (IsValid(Watched))
    {
        Watched->OnHealthChanged.RemoveDynamic(this, &AArenaScoreKeeper::HandleHealthChanged);
        Watched->OnDied.Remove(DiedHandle);              // or RemoveAll(this)
    }
    Super::EndPlay(Reason);
}
Bind with Lifetime safety
AddUObject, AddWeakLambda, AddDynamic the delegate holds a weak reference to the object; a dead object is skipped
AddRaw (plain C++ object), AddLambda capturing this none: if the object dies first, the next Broadcast crashes
AddSP (shared pointer) weak shared-pointer reference

Two traps. Binding the same function twice with AddDynamic is a mistake the engine reports (or, depending on the build, quietly calls you twice); bind once in BeginPlay, or use AddUniqueDynamic when a bind can repeat. And a lambda that captures this easily outlives this.

A runnable model of a multicast delegate

The model has the three behaviours worth understanding: handles for removal, automatic skipping of listeners whose owner has died (like AddUObject/AddWeakLambda), and safe removal during a broadcast. The engine handles that last case by marking entries and compacting afterwards.

cpp · try it yourself
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

template <typename... Args>
class MulticastDelegate {
    struct Binding { int Handle; std::weak_ptr<void> Owner; bool HasOwner; std::function<void(Args...)> Fn; bool Removed = false; };
    std::vector<Binding> Bindings;
    int NextHandle = 1;
    int Broadcasting = 0;

public:
    int AddLambda(std::function<void(Args...)> fn) {
        Bindings.push_back({NextHandle, {}, false, std::move(fn)});
        return NextHandle++;
    }
    int AddWeak(std::shared_ptr<void> owner, std::function<void(Args...)> fn) {
        Bindings.push_back({NextHandle, owner, true, std::move(fn)});
        return NextHandle++;
    }
    void Remove(int handle) {
        for (auto& b : Bindings) if (b.Handle == handle) b.Removed = true;   // compacted after broadcast
        if (!Broadcasting) Compact();
    }
    void Broadcast(Args... args) {
        ++Broadcasting;
        for (size_t i = 0; i < Bindings.size(); i++) {
            Binding& b = Bindings[i];
            if (b.Removed) continue;
            if (b.HasOwner && b.Owner.expired()) { b.Removed = true; continue; }   // owner gone: skip
            b.Fn(args...);
        }
        if (--Broadcasting == 0) Compact();
    }
    size_t Num() const { return Bindings.size(); }

private:
    void Compact() { std::erase_if(Bindings, [](const Binding& b) { return b.Removed; }); }
};

struct Widget { std::string Name; };

int main() {
    MulticastDelegate<float, float> OnHealthChanged;

    auto hud = std::make_shared<Widget>(Widget{"HUD"});
    auto popup = std::make_shared<Widget>(Widget{"DamagePopup"});
    OnHealthChanged.AddWeak(hud, [w = hud.get()](float h, float d) { std::cout << "  " << w->Name << ": bar at " << h << "\n"; });
    OnHealthChanged.AddWeak(popup, [w = popup.get()](float, float d) { std::cout << "  " << w->Name << ": " << d << "\n"; });

    int onceHandle = 0;
    onceHandle = OnHealthChanged.AddLambda([&](float h, float) {
        std::cout << "  achievement: first hit taken (unbinding itself)\n";
        OnHealthChanged.Remove(onceHandle);                     // removal during broadcast is safe
    });

    std::cout << "hit 1\n";
    OnHealthChanged.Broadcast(80, -20);
    std::cout << "popup widget closed\n";
    popup.reset();
    std::cout << "hit 2\n";
    OnHealthChanged.Broadcast(55, -25);
    std::cout << "bindings left: " << OnHealthChanged.Num() << "\n";
}
hit 1
  HUD: bar at 80
  DamagePopup: -20
  achievement: first hit taken (unbinding itself)
popup widget closed
hit 2
  HUD: bar at 55
bindings left: 1

After hit 1 the achievement removed itself; after the popup was destroyed, hit 2 skipped and dropped its binding instead of calling into freed memory. The AddLambda binding had no owner, so it is the one kind the delegate could never have protected.

Test yourself

Which delegate type can a designer bind to in a Blueprint with an 'Assign' node?

  1. DECLARE_MULTICAST_DELEGATE
  2. DECLARE_DELEGATE
  3. DECLARE_DYNAMIC_MULTICAST_DELEGATE with a BlueprintAssignable UPROPERTY
  4. Any of them

Why must a function bound with AddDynamic be a UFUNCTION?

  1. For performance
  2. Dynamic delegates bind by function name through reflection
  3. To make it const
  4. To replicate it

Which binding risks a crash if the listening object is destroyed and nobody unbinds it?

  1. AddUObject
  2. AddWeakLambda
  3. AddLambda capturing a raw this
  4. AddDynamic