Toggle Visibility of a UUserWidget C++ v4.10

Hello. I’ve gone through the tutorial on how to setup a UUserWidget with C++ and everything seems to be working correctly. I’m using the ESC key to toggle the “Pause Menu” UUserWidget on and off. Everything works great (menu turns on and off as designed) until about the 30 seconds to a minute of gameplay then it immediately crashes when trying to toggle the menu on/off.

The game runs fine otherwise and everything compiles. The Widget blueprint for the menu contains no script and graphically displays two buttons contained in a canvas. This problem exists in both the viewport in UE4 and standalone mode.

Here is the line it crashes on:
…Engine\Source\Runtime\UMG\Private\UserWidget.cpp : Line 549

bool UUserWidget::GetIsVisible() const
{
	return FullScreenWidget.IsValid(); // <-- Crash
}

Below is my code:

— PlayerController.h —

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = HUD)
    TSubclassOf<class UUserWidget> wPauseMenu;
  UUserWidget* m_PauseMenu;

— PlayerController.cpp —

#include "Blueprint/UserWidget.h"

...

void APlayerController::BeginPlay()
{
  Super::BeginPlay();

  if (wPauseMenu != nullptr)
  {
    m_PauseMenu = CreateWidget<UUserWidget>(GetWorld(), wPauseMenu);
  }
}

void APlayerController::ShowHidePauseMenu()
{
  if (m_PauseMenu != nullptr)
  {
    if (m_PauseMenu->GetIsVisible() == false)
    {
      m_PauseMenu->AddToViewport();

      FInputModeGameAndUI Mode;
      Mode.SetWidgetToFocus(m_PauseMenu->GetCachedWidget());
      SetInputMode(Mode);
      bShowMouseCursor = true;
    }
    else
    {
      m_PauseMenu->RemoveFromViewport();

      FInputModeGameOnly GameMode;
      SetInputMode(GameMode);
      FSlateApplication::Get().SetUserFocusToGameViewport(0, EFocusCause::SetDirectly);
      bShowMouseCursor = false;
    }
  }
}

Please note that I’ve tried the following: (Each results in the same crash)

  1. Using m_PauseMenu->RemoveFromParent(); instead of m_PauseMenu->RemoveFromViewport();

  2. Using SetPositionInViewport(…) to move the menu off screen when not in use


Please let me know what I’m doing wrong?

Crashes occurring within a minute after doing something is nearly always related to null references arising from garbage collection in my experience.

First thing I checked was your widget declaration, and I’d bet that it’s because of garbage collection. You MUST decorate unreal objects with UPROPERTY() to prevent them from being garbage collected, e.g

UPROPERTY( )
UUserWidget* m_PauseMenu;

The first time I ran into this kind of problem it took me 3 days to figure it out. It was a hard lesson.

Awesome. Thank you. :slight_smile: