Is there a reason why my PlayerController class fails to grab my PawnMovementComponent

Hello all, I’m trying to get movement down on my game and but every time I try to call a function for my movement component I get a crash and it looks like my PawnMovementComponent is null. Here is my custome Player Controller .h and .cpp

#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "PlayerShipController.generated.h"

class APlayerShip;
class SPACEGAME_API APlayerShipController : public APlayerController



UPawnMovementComponent* PlayerMovementComp;

virtual void SetupInputComponent() override;

void XAxisMove(float AxisValue);
void ZAxisMove(float AxisValue);

virtual void BeginPlay() override;

#include "GameFramework/Character.h"
#include "GameFramework/PawnMovementComponent.h"
#include "GameFramework/Controller.h"
#include "PlayerCharacter.h"
#include "PlayerShipController.h"



void APlayerShipController::BeginPlay()
PlayerMovementComp = GetPawn()->GetMovementComponent();
ensure(PlayerMovementComp != nullptr);

void APlayerShipController::SetupInputComponent()

InputComponent->BindAxis("XAxis", this, &APlayerShipController::XAxisMove);
InputComponent->BindAxis("ZAxis", this, &APlayerShipController::ZAxisMove);

void APlayerShipController::XAxisMove(float AxisValue)
PlayerMovementComp->AddInputVector(FVector(1.f, 0.f, 0.f)); //This is where the crash happens
//UE_LOG(LogTemp, Warning, TEXT("MoveUP"));

void APlayerShipController::ZAxisMove(float AxisValue)
//UE_LOG(LogTemp, Warning, TEXT("MoveDown"));

The PawnMovementComponent is modeled off of the DefualtPawn (I put the code into my custom Pawn class) and here are the snippets from the .h and in the .cpp file that I think are important:

//for .h
virtual UPawnMovementComponent* GetMovementComponent() const override;
UPawnMovementComponent* MovementComponent;

//for .cpp
MovementComponent = CreateDefaultSubobject<UPawnMovementComponent, UFloatingPawnMovement>(TEXT("MovementComp"));
MovementComponent->UpdatedComponent = MainComponent;

UPawnMovementComponent* APlayerCharacter::GetMovementComponent() const
return MovementComponent;

I looked over, and I don’t think I missed anything. Is there anything in particular that would be causing the crash?

Change BeginPlay() to OnPossess() and it should work I think. But to be honest, movement logic is better suited to be handled by the pawn/character itself.

^ Uhh yeah what Strife said. You are on the right track but getting the pawns movement component is a bit weird. What would be much better:

  • define a XAxisMove() function in PlayerController (you did that)
  • define a XAxisMove() function in the Pawn (todo)
  • Possess() the Pawn with the PlayerController
  • XAxisMove() in the PlayerController() should now call PossessedPawn->XAxisMove()

Thus your player controller can command and control any Pawn that has an encapsulated function called XAxisMove(). Do that either by inheritance from a base Pawn or via Interface.