"this was nullptr" on creating a widget

Hi, I am trying to create a widget from a custom player controller. When trying to set an instance to a UUserWidget object, I get an exception: “this was nullptr”. Even when checking, whether the widgets instance is a nullptr, i am getting this exception.

Header:

UUserWidget* Widget;

void OpenUserWidget(TSubclassOf<UUserWidget> widget);

Implementation:

void AMyPlayerController::OpenUserWidget(TSubclassOf<UUserWidget> widget)
{
	if (widget)
	{
		if (!Widget) // Exception here
		{
			AMyPlayerController* playerController = Cast<AMyPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0));
			Widget = CreateWidget<UUserWidget>(playerController, widget); // Exception here, when not apllying the nullcheck
		}
		if (!Widget->GetIsVisible())
		{
			Widget->AddToViewport();
		}
		FInputModeUIOnly Mode;
		Mode.SetWidgetToFocus(Widget->GetCachedWidget());
		SetInputMode(Mode);
		bShowMouseCursor = true;
	}
}

Does anybody know, what is wrong?

Unfortunately, that’s not solving the problem.

It may not like that type of check on a UObject. You could use a bool to store whether you have created it or use the IsValid() function.

if(!IsValid(Widget))

What is the exception that is being thrown?

You do realize that you are trying to get access to the player controller from within the player controller class which means its attempting to access itself?

It’s an Access Violation Exception.

I found the code above here (top answer): [C++] Create Widget - UI - Epic Developer Community Forums
They used “this” instead. I tried that first and changed it, because I thought, that “this” in the error message might actually be the “this” I was passing to CreateWidget()-function.

Actually, it was “this”, the Player Controller, causing the error. I forgot to add the newly created custom Player Controller to the GameMode, thus, the old PlayerController was in use and the methods, I was calling, were not available. Stupid me :slight_smile: