Download

How to get Player Controller reference from winthin a different class?

I know this might seem like a basic question but I’m haveing quite the trouble getting a reference of the player controller.

figured it out:
APlayerController* const PlayerController = Cast<APlayerController>(GEngine->GetFirstLocalPlayerController(GetWorld()));

You can also use


APlayerController* PC = UGameplayStatics::GetPlayerController(this, 0);

in


#include "Kismet/GameplayStatics.h"

Any Actor already include this.

What is the difference between those two?



APlayerController* PC = UGameplayStatics::GetPlayerController(this, 0);

APlayerController* const PlayerController = Cast<APlayerController>(GEngine->GetFirstLocalPlayerController(GetWorld()));

if we do not consider a cast to class?

thank you!

In your example there is no difference besides one being const and the other isn’t, however GetFirstLocalPlayerController can only return the first PlayerController while the other could return any PlayerController by Index.

If you just want the the First PlayerController you could also write it like this using the template function


    if (auto PC = GWorld->GetFirstPlayerController<ACustomPlayerController>())
    {

    }