Heya.
This past month I’ve really gotten into Unreal Engine 5.2 and nothing has really stumped me so far, except this issue I’ve been trying to fix.
So for each item in an array I had, I wanted to create a button and have each specific button when pressed do essentially the same code, but use the specific corresponding item for it’s execution.
It should be easy enough to do with a map and all, I just can’t figure out a way to get the specific button which is being pressed and calling the function. I figured I could just parse the button as an argument to the function, but that turned out harder than I thought it’d be.
I’ve tried some different things including using lambdas, making my own custom delegates, etc. but I still can’t seem to find a way to add a way to parse arguments to a function bound to an FOnButtonClickedEvent.
Ideally it would look something like this:
for(Foo item : items){
UButton* Button = NewObject<UButton>(this);
Button->OnClicked.AddDynamic(this, &AClass::OnButtonClick);
}
void AClass::OnButtonClick(UButton* Button){
// Logic using specified button here.
}
However, that obviously doesn’t work.
I instead tried doing it with a lambda, but since FOnButtonClickEvent doesn’t have a BindLambda function, I thought of making my own delegate with something like.
DECLARE_DELEGATE_OneParam(FButtonClickedDelegate, UButton*);
for(Foo item : items){
UButton* Button = NewObject<UButton>(this);
FButtonClickedDelegate ButtonClickedDelegate;
ButtonClickedDelegate.BindUObject(this, &AClass::OnButtonClick);
Button->OnClicked.Add(ButtonClickedDelegate);
}
void AClass::OnButtonClick(UButton* Button){
// Logic using specified button here.
}
However, I can’t find a way to convert my custom delegate to a TScriptDelegate.
I was hoping maybe this would work:
TScriptDelegate ButtonClickedDelegate;
ButtonClickedDelegate.BindUFunction(this, FName("OnButtonClick"));
Button->OnClicked.Add(ButtonClickedDelegate);
However it just crashes unreal as I’d expected. I’m not really sure how I’d get this to work even after searching around for a few hours.
Any and all help would be great. Thank you in advance!