Download

Can't fetch own PlayerState in a multiplayer game, but only sometimes

I’m having this issue I’ve scratched my head over a long time, and it doesn’t make much sense to me. When I try to fetch the PlayerState on my character, it sometimes goes through and sometimes doesn’t. What I mean is, if I start 3-4 instances of the game in editor, occasionally, like once every three tries, the GetPlayerState() command would fail on one of the clients. I realize the various states/controllers, etc. take a little time to be replicated all across, so I even tried doing it with a little delay




void ASandboxCharacter::BeginPlay()
{
Super::BeginPlay();

FTimerHandle DelayedFetchComponent;
GetWorld()->GetTimerManager().SetTimer(DelayedFetchComponent, this, &ASandboxCharacter::EnsureComponentsFetched, 1.0f, false);
}

void ASandboxCharacter::EnsureComponentsFetched()
{
MyController = Cast<ASandboxController>(GetController());
if (MyController)
{
MyPlayerState = Cast<ASandboxPlayerState>(MyController->PlayerState);
}
if (!MyPlayerState)
{
MyPlayerState = Cast<ASandboxPlayerState>(GetPlayerState());
}
}



Even after trying to get PlayerState both ways, it fails on occasion. Any ideas why?

Replication order of actors is not garaunteed nor deterministic, so multiplayer is subject to race conditions. When it comes to BeginPlay(), you can’t garauntee that an actor will have replicated beforehand.

The Pawn class has a replication callback for the PlayerState (OnRep_PlayerState), so you can override that and add your initialization code there.

@TheJamsh Thanks for the reply. That most definitely looks like the cleaner and most appropriate way to do it so I changed it to that. New problem though - now all the clients work fine but OnRep_PlayerState() is NEVER called on the Server. So essentially now, all the clients work fine every time except the Server. Any ideas how I can sort this out? Thanks!