Hi, I’m going to share my implementation of this lecture because Sam did an edit later on and talked about a better approach using UUserWidget::OnLevelRemovedFromWorld. I’m doing this in case someone is struggling. So here it is:
#include "MyUserWidget.h"
#include "MenuInterface.h"
#include "Components/Button.h"
bool UMyUserWidget::Initialize()
{
bool Succes = Super::Initialize();
if (!Succes) return false;
if (!ensure(Host != nullptr)) return false;
Host->OnClicked.AddDynamic(this, &UMyUserWidget::HostServer);
return true;
}
void UMyUserWidget::SetMenuInterface(class IMenuInterface* MenuInterface)
{
this->MenuInterface = MenuInterface;
}
void UMyUserWidget::Setup()
{
//Add Widget to viewport
this->AddToViewport();
UWorld* World = GetWorld();
if (!ensure(World != nullptr)) return;
//Get hold of the player controller
PlayerController = World->GetFirstPlayerController();
if (!ensure(PlayerController != nullptr)) return;
//Setting the input mode so it's able to interact only with the UI
FInputModeUIOnly InputModeData;
InputModeData.SetWidgetToFocus(this->TakeWidget());
InputModeData.SetLockMouseToViewportBehavior(EMouseLockMode::DoNotLock);
PlayerController->SetInputMode(InputModeData);
//Makes the mouse cursor show on the screen
PlayerController->bShowMouseCursor = true;
}
//Method called when the world is being destroyed
//Override method, change the input mode to game only and hides the mouse cursor
void UMyUserWidget::OnLevelRemovedFromWorld(ULevel * InLevel, UWorld * InWorld)
{
Super::OnLevelRemovedFromWorld(InLevel, InWorld);
FInputModeGameOnly InputModeData;
PlayerController->SetInputMode(InputModeData);
PlayerController->bShowMouseCursor = false;
}
void UMyUserWidget::HostServer()
{
///UE_LOG(LogTemp, Warning, TEXT("Hosting Server!"));
MenuInterface->Host();
}
The above chunk of code is placed in the MainMenu.cpp. As you can see, implementing the UUserWidget::OnLevelRemovedFromWorld method is the only thing neccesary to add to make this work as expected.
Greetings! Keep the momentum going!