How to pass a function as parameter of UFUNCTION() function?

Hello there!

So I am trying to pass a function to another function, similair to the FTimerManager.SetTimer.

I just can’t get it to work. I have looked a little into TFunction and TFunctionRef, but I couldn’t find good enough sources for me. Lamdba’s could be another way to go I heard, but I also have heard of function pointers.
Where do I start? And where are good sources/examples.

I am fine with only taking void functions with no parameters. As for why I am trying to do this, I am trying to expose some of the multithreading capabilities to blueprints.

Thanks in advance

TFunction is what you need. Anything else is just more work and unneeded complication for me.

Declare a function then add TFunction as a parameter.

void MyFunction( TFunction<void(int32 Numparam)> MyFunctionToCall)

TFunction works like std::function in normal C++ therefore, “void” is the function’s return type and anything inside the ( ) is the parameters, which can be left empty.

TFunction can’t be a parameter in a UFUNCTION() so keep that in mind.

A simpler way to use function pointers is with a typedef. There is a great tutorial which I link below:

Thank for your answer, seems good for c++, but I need it to be UFUNCTION() for blueprints. How would I go around that?

I now have it working with a delegate, it should work, but it would be nicer if I can pass a function name or something from the BP.

For people looking at this later this is how the delegate works:
C++:
DECLARE_DYNAMIC_DELEGATE(FunctionDelegate);

UCLASS(...)
.....

UFUNCTION(...)
void CreateThread(FunctionDelegate functor) { functor.ExecuteIfBound(); }

BP:

2 Likes

You could add a 2nd function which will be a UFUNCTION() and pass it the return value of your TFunction and use that 2nd function to expose the value in BP. Other than that, yes delegates are a bit more complex but it is the way unreal adds function calls on runtime.

You may need to pass the parameter as a reference.
Didn’t work for me without it.

Example:

UFUNCTION(...)
void CreateThread(FunctionDelegate& functor) { functor.ExecuteIfBound(); }
1 Like

What UFUNCTION specifiers did you use to make it available in blueprint? I tried blueprint callable but that didn’t seem to work.

What UFUNCTION specifiers did you use to make it available in blueprint? I tried blueprint callable but that didn’t seem to work.