Why does GetPlayerController() returns nullptr in C++ but proper value in Blueprints?

My Case

Briefly, in construction script I have some logic which uses Player Camera Manager, but when I call the same exact function but from inside c++ function i get an engine crash due to access violation. I did some debugging and found out that Player Controller is not yet instanced by the time I try to access it.

Blueprints

So when I call the pure function GetPlayerCameraManager (which implicitly calls UGameplayStatics::GetPlayerController) in Blueprints, everything works as intended.

I have something like this in my code (oversimplified):

  • Construction Script

338232-construction-script.png

  • The function that calls Get Player Camera Manager

338233-get-player-camera-manager.png

The Problem

In the base class that my Blueprint is based on I added this function:

void ATestActor::CallGetPlayerCameraManager()
{
	APlayerCameraManager* CameraManager = UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0);
	if (IsValid(GEngine))
		GEngine->AddOnScreenDebugMessage(0, 3.f, FColor::Red, CameraManager->GetName());
}

Then when I try to call this function in construction script the engine crashes:

338234-c-construction-script.png

Most importantly, the debugger shows that the problem is that UGameplayStatics::GetPlayerController() (which is used in GetPlayerCameraManager()) returns nullptr. The question therefore is why this happens and how can I change my code for it to work

Have you tried running the function off of the BeginPlay event, as opposed to the Construction Strip?

It’s probably returning null because the PlayerController hasn’t been created yet. Try calling it after the constructors e.g. from BeginPlay or PostInitializeComponents.

Why though it works in blueprints? And why can’t I call the same exact function from c++. It’s crucial for my implementation because I need my Level Designers to see the result before BeginPlay() (it must be visible in the viewport) So that’s the problem. Could you give any advice on that?