Displaying and hiding a sheet of UMG elements in-game

So we have already discussed how to add a widget to the viewport, which means that it will be rendered on the player's screen.

However, what if we want to have UI elements that are toggled based on other factors, such as proximity to certain Actors, or a player holding a key down, or if we want a UI that disappears after a specified time?

How to do it...

  1. Create a new GameMode class called ToggleHUDGameMode.
  2. Override BeginPlay and EndPlay.
  3. Add the following UPROPERTY:
    UPROPERTY()
    FTimerHandle HUDToggleTimer;
  4. Lastly add this member variable:
    TSharedPtr<SVerticalBox> widget;
  5. Implement BeginPlay with the following code in the method body:
    void AToggleHUDGameMode::BeginPlay() { Super::BeginPlay(); widget ...

Get Unreal Engine 4 Scripting with C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.