Communicate between PlayerController and Character

I was wondering: what is an elegant way (Epic-recommended) to be able to have a two-way communication/access between a custom PlayerController and custom Character. What I mean is, say I have derived from the standard classes that come with the engine and I have MyGamePlayerController, and MyGameCharacter c++ classes. Whenever I use the standard given “GetController()” or “GetCharacter” (or GetPawn or GetControlled Pawn or whatever), I always have to worry about casting.

What shall I do? Is it an ok practice to keep casting whenever I need this two classes to refer to each other? Is it better to create references to each other in the definition of each class, by taking care of casting only once in each case, so that I don’t have to worry about it?

Any thoughts appreciated.

I would say it’s okay to cast freely in c++. If you look at epic’s implementation of pawn and controller, they also cast when they need to.

Casting is fine - but you shouldn’t do it more often than necessary.

For example, in MyGameCharacter.h:

public:

	class AMyPlayerController* MyPlayerController = nullptr;

Then, in MyPlayerController.h

class MyGameCharacter* ControlledPawn = nullptr;

virtual void OnPossess(APawn* PossessedPawn) override;

And then in MyPlayerController.cpp

void MyPlayerController::OnPossess(APawn* PossessedPawn)
{

	Super::OnPossess(PossessedPawn);

	ControlledPawn = Cast<AMyGameCharacter>(PossessedPawn);
	if (ControlledPawn)
	{
		ControlledPawn->MyPlayerController = this;
	}
}

Unless you have many different playercontroller and/or characters, that should be sufficient.

1 Like

Thanks man. I was starting to lean towards that solution myself. I was about to do this via begin play, but I like your approach with the Possess method too… Even if I only cast a few times, my code right now is fluid and not final so in the future it can improve speed and workflow if I have just one reference in each class to use freely.