Check if player state in the PlayerArray is the local player's or not?

Hey,

I’m looping through the PlayerArray to create a widget for each player in the lobby. However, I don’t want to create a widget for the local player. This is what I have right now, it works fine, but surely there is a better way of doing this?



// This code works, but is there a better way of doing this?
for (APlayerState* Player : GetLobbyGameState()->PlayerArray)
{
     APlayerController* LocalPlayerController = GetWorld()->GetFirstPlayerController();
     if (LocalPlayerController)
     {
          if (LocalPlayerController->PlayerState && Player->GetUniqueId() == LocalPlayerController->PlayerState->GetUniqueId())
          {
                // Current player is the local player. Skipping widget creation.
                continue;
          }
     }

     // Creating widget for player...
}


Is this widget something that needs to be replicated to other players? Is the local player always the host, or is it sometimes not?

If the server spawns a Pawn or Actor and set its Owner during spawning then you can simply check if that pawn is locally controlled, or if it is an Actor check if the owner equals the local PlayerController. It is important that the owner is set while spawning otherwise IsLocallyControlled could be false at BeginPlay since it hasn’t been replicated yet.

In case you have no Pawn or to be sure you can use PlayerState->HasLocalNetOwner()

1 Like