Hi, I’ve been struggling to understand a particular behavior in Unreal Engine’s multiplayer system. I must admit, I haven’t deeply read the official documentation. I intentionally approach it this way because seeing the solutions Unreal Engine provides for the challenges I face helps me better understand why those solutions are important.
Now, my question is: I want a client to receive a unique ID when connecting to the server. Then, I want the client to reflect this ID on its own UTextRenderComponent
. This update should be handled only by the client itself, without the server or other clients being aware of it.
Here's the code I’ve written:
AMyPlayerState.h (not have a constructor)
public:
FORCEINLINE void SetUniquePlayerID(int32 NewID) { UniquePlayerID = NewID; };
FORCEINLINE int32 GetUniquePlayerID() const { return UniquePlayerID; };
protected:
int32 UniquePlayerID = 0;
AMyCharacter.h
private:
UPROPERTY(EditAnywhere)
class UTextRenderComponent* PlayerName;
AMyCharacter.cpp
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
if (IsLocallyControlled())
{
AMyPlayerState* PS = Cast<AMyPlayerState>(GetPlayerState());
if (PS && GEngine)
{
GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Cyan,
FString::Printf(TEXT("UniquePlayerID: %d \t Name: %s"), PS->GetUniquePlayerID(), *PS->GetName()));
PlayerName->SetText(FText::AsNumber(PS->GetUniquePlayerID()));
}
}
}
AMyGameMode.h
protected:
virtual void PostLogin(APlayerController* NewPlayer) override;
int32 UniquePlayerID = 0;
AMyGameMode.cpp
AMyGameMode::AMyGameMode()
{
PlayerStateClass = AMyPlayerState::StaticClass();
}
void AMyGameMode::PostLogin(APlayerController* NewPlayer)
{
Super::PostLogin(NewPlayer);
if (NewPlayer && HasAuthority())
{
AMyPlayerState* NewPlayerPS = Cast<AMyPlayerState>(NewPlayer->PlayerState);
if (NewPlayerPS)
{
int32 AssignedID = ++UniquePlayerID;
NewPlayerPS->SetUniquePlayerID(AssignedID);
}
}
}
In the output, the clients know neither about the server nor about the clients. So seeing the default value of UTextRenderComponent
is what I expected, and from the server’s point of view, the state of the clients is also what I expected. However, only the server itself seems to have updated UTextRenderComponent
. This is something I didn’t expect.