- Create a new GameModeBase class called ToggleHUDGameMode:

- Add the following UPROPERTY and function definitions to the ToggleHUDGameMode.h file:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "SlateBasics.h"
#include "ToggleHUDGameMode.generated.h"
UCLASS()
class CHAPTER_14_API AToggleHUDGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
UPROPERTY()
FTimerHandle HUDToggleTimer;
TSharedPtr<SVerticalBox> widget;
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
};
- Implement BeginPlay with the following code in the method body:
void AToggleHUDGameMode::BeginPlay()
{
Super::BeginPlay();
widget = SNew(SVerticalBox)
+ SVerticalBox::Slot()
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SButton)
.Content()
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("Test button")))
]
];
auto player = GetWorld()->GetFirstLocalPlayerFromController();
GEngine->GameViewport->AddViewportWidgetForPlayer(player, widget.ToSharedRef(), 1);
auto lambda = FTimerDelegate::CreateLambda
([this]
{
if (this->widget->GetVisibility().IsVisible())
{
this->widget->SetVisibility(EVisibility::Hidden);
}
else
{
this->widget->SetVisibility(EVisibility::Visible);
}
});
GetWorld()->GetTimerManager().SetTimer(HUDToggleTimer, lambda, 5, true);
}
- Implement EndPlay:
void AToggleHUDGameMode::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
GetWorld()->GetTimerManager().ClearTimer(HUDToggleTimer);
}
- Compile your code and start the editor.
- Within the Editor, open World Settings from the toolbar:

- Inside World Settings, override the level's Game Mode to be our AToggleHUDGameMode:

- Play the level and verify that the UI toggles its visibility every five seconds.