Using a TFunction instead of calling functions

I spotted someone else added a delegate instead of firing functions on classes. I opted for passing a TFunction through and calling that from the Session button instead.

MainMenu.cpp

void UMainMenu::SetActiveSessions(TArray<FString>& InSessionNames)
{
	ScrollBox_ActiveSessions->ClearChildren();
	int32 CurrentIndex = 0;
	for (FString& SessionName : InSessionNames)
	{
		if (UJoinActiveSessionButton* JoinButton = CreateWidget<UJoinActiveSessionButton>(this, JoinActiveSessionButtonClass))
		{
			TWeakObjectPtr<UMainMenu> WeakThis(this);
			TFunction<void (uint32)> Response([WeakThis](const uint32 InIndex)
				{
					if (UMainMenu* StrongThis = WeakThis.Get())
					{
						StrongThis->SelectIndex(InIndex);
					}
				});

			JoinButton->Setup(SessionName, CurrentIndex, Response);

			ScrollBox_ActiveSessions->AddChild(JoinButton);
			++CurrentIndex;
		}
	}
}

JoinActiveSessionButton.h

	void Setup(const FString& InSessionName, const int32 InIndex, TFunction<void (uint32)>& InButtonClickResponse);

	TFunction<void(uint32 Index)> ButtonClickResponse;

	uint32 ButtonIndex;

JoinActiveSessionButton.cpp

bool UJoinActiveSessionButton::Initialize()
{
	if (!Super::Initialize()) return false;

	if (!Button_JoinSession) return false;

	Button_JoinSession->OnClicked.AddDynamic(this, &UJoinActiveSessionButton::SessionSelected);

	return true;
}

// ----------------------------------------------------------------------

void UJoinActiveSessionButton::Setup(const FString& InSessionName, const int32 InIndex, TFunction<void(uint32)>& InButtonClickResponse)
{
	Text_SessionName->SetText(FText::FromString(InSessionName));

	ButtonClickResponse = InButtonClickResponse;
	ButtonIndex = InIndex;
}

// ----------------------------------------------------------------------

void UJoinActiveSessionButton::SessionSelected()
{
	if (ButtonClickResponse)
	{
		ButtonClickResponse(ButtonIndex);
	}
}```
1 Like

Privacy & Terms