Events (Python)

Subscribing to events defined in C++

Updated over 3 years ago Edit Page Revisions

Binding to an event from Python requires slightly different syntax than developers might be used to from C++; Unreal provides custom methods specifically to support binding from the Python scripting environment. For instance, in the MulticastDelegateBase:

  • add_function(obj, name) Requires an instance of a class that inherits from UObject (with all the necessary decorators, if implemented in Python), and the string name of the UFunction that should be called upon it. Unless you already have a UClass to which you can add a suitable handler method, this might require additional boilerplate code.

  • add_callable(callable) Accepts a raw Python function without the need for Unreal decorators, even one declared outside of a class.

There are also _unique variants to ensure that event handlers are only added once, contains_ functions to check they exist, and remove_ functions to unbind them. The non-multicast DelegateBase has similar functionality, but its subscribers are named bind_function and bind_callable respectively.

A full listing of these functions can be found in the Unreal Python API documentation:

Sample

C++

DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FCustomEvent, FString, InArg);

UCLASS()
public class MyClass : public UObject
{
    GENERATED_BODY();
public:
    UPROPERTY(BlueprintAssignable)
    FCustomEvent MyEvent;
}

Python

def my_event_handler(in_arg):
    unreal.log("Event Handled"!)

my_instance = MyClass()
my_instance.my_event.add_callable(my_event_handler)