Removefromparent() does not work

Hello, I’m trying to display and toggle a widget (like a menu screen when hit esc) using c++. I was able to display the widget but wasn’t able to toggle it on and off. The code is below
GameState.cpp

void AMyGameStateBase::SetVisible(bool v)
{
	Visible = v;
}

bool AMyGameStateBase::GetVisible()
{
	return Visible;
}

NOTE: Visible is defined as bool in header file and initialized to false

MyPlayerController.cpp

void AMyPlayerController::Inventory() {
	AMyGameStateBase* GameState = Cast<AMyGameStateBase>(GetWorld()->GetGameState());

	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, FString::Printf(TEXT("%i"), GameState->GetVisible()));
	

	if (Widgets && GameState) {
		InventoryWidget = CreateWidget<UUserWidget>(this, Widgets);
		
		if (InventoryWidget) {
			if (GameState->GetVisible() == true) {
				GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue,TEXT("Hello!!!!"));
				InventoryWidget->RemoveFromParent();
				GameState->SetVisible(false);
			}
			else {
				InventoryWidget->AddToViewport();
				GameState->SetVisible(true);
			}

		}
	}
}

PlayerCharacter.cpp

void Apractice_cppCharacter::Inventory() {
	AMyPlayerController* Controller = Cast<AMyPlayerController>(GetWorld()->GetFirstPlayerController());
	if (Controller) {
		Controller->Inventory();
	}
}

and inventory() is called by using:

	PlayerInputComponent->BindAction("Inventory", IE_Pressed, this, &Apractice_cppCharacter::Inventory);

Any help is appreciated, thanks in advance!

1 Like

You have no reference to the widget you have created.

Currently your code will always create a new InventoryWidget and add it to the screen, it will never get removed.

InventoryWidget = CreateWidget<UUserWidget>(this, Widgets);

This line will always create a widget, your previously created widget no longer has a reference and is now just in memory.

Thank you so much!!! Got it figured out based on your reply!