How to do it...

  1. Create a new GameModeBase class called ToggleHUDGameMode:

  1. 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;
};
  1. 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);
}
  1. Implement EndPlay:
void AToggleHUDGameMode::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
GetWorld()->GetTimerManager().ClearTimer(HUDToggleTimer);
}
  1. Compile your code and start the editor.
  2. Within the Editor, open World Settings from the toolbar:

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

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