Accessing specific Pawn out of PlayerController

Assume everything is setup as in the original Question, but then make the following changes:

Insert a public SetPawn() override and a private AMyCharacter* into the Class definition of MyPlayerController:

public:

virtual void SetPawn(APawn* InPawn) override;

private:

	UPROPERTY()
	AMyCharacter* MyCharacter;

Implement the SetPawn() Method as follows:

void AMyPlayerController::SetPawn(APawn* InPawn)
{
	Super::SetPawn(InPawn);

    //Setting MyCharacter to the adress of InPawn if InPawn is a MyCharacter
	APawn* Pawn = GetPawn();
	MyCharacter = (Pawn ? Cast<AMyCharacter>(Pawn) : NULL);
}

Change the Implementation of SetupInputComponent() as follows:

void AMyPlayerController::SetupInputComponent()
     {
         // set up default Input Component
         Super::SetupInputComponent();

         // InputComponent setups which are specific to MyCharacter
         InputComponent->BindAction("KeyPressed", IE_Pressed, this, &AMyPlayerController::KeyPressed);
     }

Finally Change the KeyPressed Method into:

 void AMyPlayerController::KeyPressed()
 {
         if(MyCharacter != NULL) MyCharacter->DoStuff();
 }

Main advantages of using the given implementation are:

  • Easily extend the PlayerController to a wide variety of Characters/Pawns just by adding appropriate private Variables and extending SetPawn/SetInputComponent
  • If no GameMode is set (and the default GameMode is used) or if MyGameMode misses propper initialisation of the DefaultPawnClass to MyCharacter (such that the DefaultPawn is used) the PlayerController has a fallback mechanism to support the DefaultPawn Movement (flying around with WASD and mouse look)

Any Thoughts on this Solution?