Player has no Playerstate

Hey,

I am trying to implement a Lobby system for my game and it’s going pretty well so far. I can Host a game and choose a game to join from a server browser.

I have following setup.

MenuLevel: Default Startup Level where you can Host or join a game

LobbyLevel: When you created or joined a session you are placed in the LobbyLevel

The Lobbylevel has it’s own GameMode, PlayControllerClass and PlayerState class.

When I Host a game (create a session) everything works fine and a new PlayerController with PlayerState is created.

When I join a game (join session) a PlayerController is created but there is no PlayerState.

I try to access the PlayerState in the BeginPlay function of my PlayerController.

void AGamePlayerController::BeginPlay()
{
	Super::BeginPlay();
	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Hallo"))); 
	if (PlayerState)
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("PLAYERSTATE")));

	}
	else {
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("NOT PLAYERSTATE")));

	}}

I dont have any explenation for this. The only thing I can imagin is the way I join the Lobby. As Host I call OpenLevel() and as Client a call ClientTravel().

Ok I found the problem!

Because the PlayerState is created on the server and replicated to the client it takes some time till everything is ready to work.

I checked by just checking the PlayerState in the TickFunction. Around the 2nd tick everything should be initialized fine.

I gave an alternative solution in this question to checking/polling in Tick.Instead of polling, my solution for solving the issue where PlayerState was null/unavailable until a few frames after BeginPlay was to put my logic in an overridden version of ACharacter::OnRep_PlayerState(). This gets called as soon as the PlayerState is first assigned, or ever changes. No need to pollute your Tick method or have perf issues of checking it every frame, even when you don’t need to.