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

This code in Blueprints works:

Construction Script
Get Player Camera Manager

Though this code in C++ & Blueprints combined doesn’t:

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

C++ Construction Script

In the second case where I use C++ the engine crashes due to access violation.

Debugging showed that the problem is that PlayerController is not yet created when I call it from C++, but I don’t understand why it works perfectly fine in Blueprints. For me it’s seems strange that calling the same exact function from C++ and Bluerpints causes different results. Any ideas?
P.S. It’s crucial to have that functionality in Construction Script because my Level Designers have to see the results in the viewport BEFORE playing.

There is no player controller or player camera manager in the level editor. Your blueprint code doesn’t work either, it just doesn’t crash because it safeguards you against accessing nullptr. It is basically doing the equivalent of GetNameSafe(CameraManager).

Oh, ok thank you. Didn’t know Blueprints are so clever that they outsmart me haha. So I have to check the value before using it in c++ right?

Yes, you would have to use if (CameraManager) to check that it’s not nullptr before accessing it.

1 Like