How to use the Player Controller class in C++

You don’t actually add your Player Controller (PC) to your Character. The Character exists on its own and the PC acts upon it. The Pawn/Character shouldn’t know or care if it’s being controlled by a APlayerController or an AAIController, or any customized subclass.

To create a custom Player Controller, derive from APlayerController and customize however you wish.

To load your custom PC, you need to modify your Game Mode. You can do this in the editor by using the drop-down selections within your game mode actor in the content browser, or you can customize it within the details panel of an individual level.

You can also preset custom defaults within your C++ game mode constructor.

e.g.

ACustomPlayerController.h

#include "Runtime/Engine/Classes/GameFramework/PlayerController.h"
    
#include "ACustomPlayerController.generated.h"

/**
*
*/
UCLASS(Blueprintable, BlueprintType)
class MYGAME_API ACustomPlayerController : public APlayerController
{
	GENERATED_BODY()

	//Constructor
	ACustomPlayerController();

        //... custom code ...

};

ACustomPlayerController.cpp

#include "MyGame.h"

#include "ACustomPlayerController.h"
    
//Constructor
ACustomPlayerController::ACustomPlayerController()
	:
	APlayerController()
{
    //... custom defaults ...
}

//... custom code ...

ACustomGameMode.h

#include "GameFramework/GameMode.h"

#include "ACustomPlayerController.h"

/**
*
*/
UCLASS(Blueprintable, BlueprintType)
class MYGAME_API ACustomGameMode : public AGameMode
{
	GENERATED_BODY()

	//Constructor
	ACustomGameMode();

        //... custom code ...

};

ACustomGameMode.cpp

#include "MyGame.h"

#include "ACustomGameMode.h"
   
//Constructor
ACustomGameMode::ACustomGameMode()
	:
	AGameMode()
{

    //tell your custom game mode to use your custom player controller
	PlayerControllerClass = ACustomPlayerController::StaticClass();

	//you can set whatever (if any) other default framework classes
    //you wish for this game mode as well
	DefaultPawnClass = ACustomPawn::StaticClass();
	GameStateClass = ACustomGameState::StaticClass();
	HUDClass = ACustomGameHUD::StaticClass();
	ReplaySpectatorPlayerControllerClass = ACustomReplaySpectatorPlayerController::StaticClass();
	SpectatorClass = ACustomSpectatorClass::StaticClass();

}

//... custom code ...
3 Likes