Unreal Engine - Accept Delegates as Arguments in Blueprint Functions
In Unreal you can accept a delegate callback as an argument to a Blueprint function. This is a powerful feature that allows C++ code to manage and execute Blueprint-based events.
For example, you can register a Custom Event in Blueprint and pass it onto C++ so we can call it when a loading screen is done, a download is finished, or any other async or regularly occurring event.
Similar functionality can be achieved with Blueprint Native Events, or interfaces - however, sometimes you need the flexibility of passing around delegates like you can in C++.
To set this up, define your dynamic delegate using the
Then you need to create a const reference to your delegate as an argument, and (the most important bit) add a meta tag to the
UFUNCTION macro called
AutoCreateRefTerm that has the value of the argument you've defined. This tells Blueprint to make the argument pass-by-reference, rather than by value.
DECLARE_DYNAMIC_DELEGATE(FFooDelegate); UFUNCTION(BlueprintCallable, meta = (AutoCreateRefTerm = "Delegate")) void Bar(const FFooDelegate& Delegate);
In Blueprint, you can now access this function and pass in custom events as you wish.
In your CPP code you can now call
Delegate.ExecuteIfBound() wherever you wish to call back to Blueprint! Note: always call this from the Game Thread to avoid crashes and/or chaos.
If you want to keep this callback for later, store it as a UPROPERTY() in your class and then fire it when needed.