Out of the below mentioned ways which one is more appropriate to get player controller?

out of the below mentioned ways which one is more appropriate to get player controller? And also what is the difference between them?

1st
APlayerController * CurrentPlayerController = Cast"<“APlayerController”>"(Controller);// Without quotes. for some reason answer hub is not taking “<’'APlayerController”>" without quotes.

2nd
APlayerController * CurrentPlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);

Thank you.

On AnswerHub you can include code (without quotes) if you add it via the code window, click the 101010 icon (between quote and paper clip icons). You were probably running into problems because of the brackets and HTML formatting.

To answer your actual question, the first version:

APlayerController* CurrentPlayerController = Cast<APlayerController>(Controller);

does not actually acquire the player controller, it’s casting an already populated variable (Controller) to the class APlayerController. This only works within objects that already have the Controller variable defined (e.g. within APawn, Controller is an AController). APawn can be controlled by the player or it can be controlled by an AIController, using Cast allows your code to access members specific to that class.

The second version:

APlayerController * CurrentPlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);

uses a static method (UGameplayStatics::GetPlayerController) to collect the player controller of the given index (in this case, 0, the default first player). This can be used anywhere an object has access to GetWorld().

Determining which is more appropriate for your project depends on where and in what context you are trying to access the APlayerController.

For more details, you can see: