Skip to main content

Using EventDispatcher from C++

Every Blueprint node is a static function on UEventManager, so the C++ API matches the Blueprint API.

Setup​

Add the module to your .Build.cs:

PrivateDependencyModuleNames.AddRange(new string[] { "EventDispatcher" });

Include the header:

#include "EventDispatcherManager.h"

Callbacks must be UFUNCTIONs​

The callbacks are dynamic delegates, so the function you bind must be a UFUNCTION(). Lambdas and raw function pointers are not supported.

UCLASS()
class AScoreDisplay : public AActor
{
GENERATED_BODY()

protected:
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;

UFUNCTION()
void OnScoreChanged(int32 NewScore);

UPROPERTY(EditAnywhere)
UEventIdentifier* ScoreChangedEvent;
};

Registering​

void AScoreDisplay::BeginPlay()
{
Super::BeginPlay();

FIntEventDelegate Callback;
Callback.BindDynamic(this, &AScoreDisplay::OnScoreChanged);

UEventManager::RegisterIntEvent(this, ScoreChangedEvent, Callback);
}

The first argument is the world context and also the object that Optional Target and Unregister … By Object match against.

For a named event:

UEventManager::RegisterIntEventName(this, TEXT("ScoreChanged"), Callback);

Invoking​

UEventManager::InvokeIntEvent(this, nullptr, ScoreChangedEvent, 42);
UEventManager::InvokeIntEventName(this, nullptr, TEXT("ScoreChanged"), 42);

The second argument is the optional target. Pass nullptr to reach every listener.

Unregistering​

void AScoreDisplay::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
UEventManager::UnregisterEventByObject(this, ScoreChangedEvent, this);

Super::EndPlay(EndPlayReason);
}

Delegate types​

Event typeDelegateCallback signature
SimpleFSimpleEventDelegatevoid()
PayloadFPayloadEventDelegatevoid(UObject* Payload)
StringFStringEventDelegatevoid(const FString& String)
IntFIntEventDelegatevoid(int32 Value)
FloatFFloatEventDelegatevoid(float Value)
BoolFBoolEventDelegatevoid(bool Value)
VectorFVectorEventDelegatevoid(const FVector& Data)
String + FloatFStringFloatEventDelegatevoid(const FStringFloat& Data)
String + IntFStringIntEventDelegatevoid(const FStringInt& Data)

Inspecting the manager​

The manager is a Game Instance subsystem:

UEventManager* Manager = GetGameInstance()->GetSubsystem<UEventManager>();
const int32 NumListeners = Manager->GetNumRegisteredEvents();
const int32 NumPending = Manager->GetNumQueuedEvents();