What is the best way to get local player controller in C++?

There seems to be a few ways to get the local player controller in multiplayer.

Such as:
()->GetFirstPlayerController()

Or:
UGameplayStatics::GetPlayerController((), 0)

Or:
GEngine->GetGamePlayer(world, 0)->PlayerController

Or:
for( FConstPlayerControllerIterator Iterator = ()->GetPlayerControllerIterator(); Iterator; ++Iterator )
and then checking IsLocalPlayerController or Cast(playerController->Player)

We are wondering what the differences are between them, if any, and which one is best to use. Are some ways more reliable or efficient than others?

+1 because I also wonder about this from time to time. I currently do it so, that when I know that I’m on the client I sometimes use GetFirstPlayerController(), because on client there exists only one player controller. When I don’t know for sure, I always use the PlayerControllerIterator. I believe this must be the most reliable method. An official statement or would be much appreciated.

1 Like

Little bit of API refrence searching ;]

It’s in UEngine so use it with GEngine->

GetFirst should be the fastest as it iterates and return first find and stop looping, if you in pawn you should get controller via GetController as it is more direct. If you really worried with performance, just do it once somewhere and keep the pointer.

1 Like

So upon further exploration, all of the solutions above seem to use World to get the first player controller. The two most direct options then seem to be ()->GetFirstPlayerController() and using the PlayerControllerIterator. Seeing as GetFirstPlayerController uses PlayerControllerIterator, it just comes down to how much you control you want of your search, but GetFirstPlayerController would probably do just fine.

If you’re worried about finding the local player specifically, in multiplayer, you can also use UWorld::GetFirstLocalPlayerFromController() which will return the first LocalPlayer.

2 Likes