I get null when I get a reference of PlayerController in a method called by the PlayerController

Hi!

I have a custom player controller that call this method in a Pawn class:

void AMyPawn::DoRotation(float AxisValue)
{
	float Increment;
	AActor* ObjectToRotate = nullptr;

	if (AxisValue == 0.0)
		return;

	// Omitted for brevity.

	if (!bRotateCube)
	{
		FRotator rotator = ObjectToRotate->GetActorRotation();

		float Yaw = rotator.Yaw + FMath::RadiansToDegrees(Increment);

		APlayerController* cont = UGameplayStatics::GetPlayerController(GetWorld(), 0);
		cont->SetControlRotation({ rotator.Roll, rotator.Pitch, Yaw });
	}

}

This line UGameplayStatics::GetPlayerController(GetWorld(), 0); returns null.

I have added this to the constructor of my custom Player Controller and I can see the log in the output. This is my custom PlayerController:

#include "MyOwnController.h"
#include "MyGameModeBase.h"
#include "MyPawn.h"


AMyOwnController::AMyOwnController()
{
	UE_LOG(LogTemp, Warning, TEXT("AMyOwnController constructor"));
}

void AMyOwnController::SetupInputComponent()
{
	Super::SetupInputComponent();

	// Input controller
	InputComponent->BindAction("ZoomIn", IE_Pressed, this, &AMyOwnController::ZoomIn);
	InputComponent->BindAction("ZoomOut", IE_Pressed, this, &AMyOwnController::ZoomOut);
	InputComponent->BindAxis("MoveSideways", this, &AMyOwnController::MoveSideways);

}

void AMyOwnController::ZoomIn()
{
	Zoom(true);

}

void AMyOwnController::ZoomOut()
{
	Zoom(false);

}

void AMyOwnController::MoveSideways(float AxisValue)
{
	AMyGameModeBase* MyGameMode = Cast<AMyGameModeBase>(GetWorld()->GetAuthGameMode());
	AMyPawn* MyPawn = Cast<AMyPawn>(MyGameMode->DefaultPawnClass.GetDefaultObject());

	MyPawn->DoRotation(AxisValue);

}

I have also set up the player controller in my custom game mode class:

AMyGameModeBase::AMyGameModeBase()
{
	DefaultPawnClass = AMyPawn::StaticClass();

	PlayerControllerClass = AMyOwnController::StaticClass();
}

AS YOU CAN SEE, void AMyOwnController::MoveSideways(float AxisValue) is calling the void AMyPawn::DoRotation(float AxisValue) method, so the player controller is instantiated.

How can I get a reference of the player controller?

Thanks!

If you do this from the PCM (Player Camera Manager) instead, you will have a valid PlayerController. On the PlayerController panel (BP) or its constructor (c++) you can set the class to use for the Player Camera Manager.

PlayerCameraManagerClass = ASomePlayerCameraManager::StaticClass();

I suppose that the problem is that he tries it in the constructor. I am not sure but perhaps the Controller isn’t set, yet.

No, sorry. It is a pawn called ACameraPawn. I can change the name with MyPawn if you want.

I don’t think so. An instance of my custom PlayerController is calling this method.