How do I call a function in another object?

I have a PlayerController object and a UserWidget object.
I want to call a Spawn function in PlayerController from UserWidget.

In UserWidget:

	AMyPlayerController* playerCtrl = Cast<AMyPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0));
	if (playerCtrl) {
		UE_LOG(LogTemp, Warning, TEXT("started spawn"));
		playerCtrl->Spawn();
	}
	else
	{
		UE_LOG(LogTemp, Warning, TEXT("playerController not found"));
	}

Playercontroller:

void AMyPlayerController::Spawn()
{
	UE_LOG(LogTemp, Warning, TEXT("Start spawn"));
	AMyPlayerController* MyController = Cast<AMyPlayerController>(UGameplayStatics::GetPlayerController(this, 0));
	AMyPlayer* MyPlayer = Cast<AMyPlayer>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
	if (MyController && MyPlayer)
	{
		FLatentActionInfo LatentInfo;
		FName LevelToLoad = "Main";
		UGameplayStatics::LoadStreamLevel(GetWorld(), LevelToLoad, true, true, LatentInfo);
		MyController->Possess(MyPlayer);
	}

	UE_LOG(LogTemp, Warning, TEXT("End spawn"));
}

Currently this doesn’t find the GetWorld() in the UserWidget due to it not inheriting the GetWorld() from AActor. How do I reference PlayerController in UserWidget?

Thanks, that worked for me.

User Widgets usually have an owner - if it is the player controller you need, then you’re set. otherwise you can get world from the owner.

But I have to digress and say your spawn function looks pretty weird to me, I’d advise to name functions so that it’s clear what they do, it seems it’s more of a loading then simple spawning the player.

Best,
Janusz Tarczykowski