Is it possible to pass a function as another function's argument?
I'm working on abstracting switches and other interactions by creating a base Interaction component, whose only job is to let parent actors subscribe to its UseSubscribers event, and let outside functions call the function which broadcasts UseSubscribers. For purposes of cleanliness, I don't want external functions directly modifying the event, so I'm trying to write a function to do the subscribing for me:
This must be absurdly simple, but I'm having a lot of trouble figuring out the syntax behind it- is there a simple and recommended way to pass the function's address in memory as an argument, or should I just manually run something like ComponentRef->UseSubscribers.Add(&MyClass::MyFunction) from the actor doing the subscribing?
Yes, you can do this. You must first realize that compatibility among the delegate types is determined by their arguments. Now, declare these in your .h. You may declare them within your UInteraction class, or globally outside of the class. Either is valid.
Now, add these method signature declarations to your UInteraction declaration in the .h:
And these implementations to your .cpp:
And then, if another class wants to subscribe:
And if you wanted to unsubscribe, you would save the returned FDelegateHandle somewhere, and use it again later when calling UnsubscribeUser.
How does this work? You must understand two things:
answered Aug 21 '15 at 09:05 PM
This looks like strange delegate decleration it should be DECLARE_DYNAMIC_DELEGATE. Now, there 2 types of delegates, singlecast and multicast, singlecast takes only one function (subscriber), multicast takes more then one and you decler it using DECLARE_DYNAMIC_MULTICAST_DELEGATE. Also you should decler them outside of the class, so it cereates structs not related to class. So it should looks like this:
You can also add UPROPERTY(BlueprintAssignable) before varable so you can use delegate in blueprints as event dispacher. As for binding, your way of doing looks really wirerd to, you don't need to add function for that, object that wants to subscribe it can do that from outside of class:
and for functions outside of UObject tree you use AddRaw insted of AddDynamic. All function used in AddDynamic need to be visible by engine in reflection system, so place UFUNCTION() before there declarations (can be empty, main function of UFUNCTION is to add function in to reflection system, making function blueprint callable is just bonus feature). If you use singlecast delegate you use word "Bind" instead of "Add". To raise the event in delegate you call this:
Follow this question
Once you sign in you will be able to subscribe for any updates here