Passing Arbitrary Data to a Function

I’m working on an centralised event system where hundreds of events might fire in a single frame, and listeners subscribe to specific event types.

Data is passed along with events via a delegate with the signature:

void(TSubclassOf<UEventType> EventClass, UObject* Sender, UEventArgs* EventArgs)

The receiver casts EventArgs to the expected derived type and handles the data.

Is there a way to do this where EventArgs is instead a struct? I’m naive, so excuse me if I’m mistaken, but structs are significantly less overhead (and are better for garbage collection?) than UObjects right?

I’m creating a lot of UObjects this way. Sometimes thousands in a single frame. I’ve tried using structs where FEventArgs has derived FMySpecificEventArgs containing the params needed, but I can’t pass it as an FEventArgs* and cast to FMySpecificEventArgs* in the receiving function.

Is there some way to be polymorphic with UStructs?

I think I found a solution using StructUtils / FInstancedStruct. I would appreciate any knowledgeable person’s advice if this is actually better than just sending UObjects as EventArgs.

Assuming the signature:

void(TSubclassOf<UEventType> EventClass, UObject* Sender, FInstancedStruct& EventArgs);

Evoke the event using:

FMyDerivedEventArgs newEventArgs;
FInstancedStruct wrapper = FInstancedStruct::Make(newEventArgs);
BroadcastEvent(EventClass, Sender, wrapper);

In the receiving function, attempt to get a pointer to the correct type:

if (const FMyDerivedEventArgs* AsDerivedType = EventArgs.GetPtr<FMyDerivedEventArgs>())
{
    DoSomething();
}
else
{
    // Not the correct EventArgs type
}

Do you need blueprint support ?

Not currently, but I might in the future and would appreciate any info you could provide!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.