GameState PlayerArray Example C++

Hey Everyone!

I recently went through this multiplayer chat HUD tutorial.

Everything works just fine in blueprints.

I wanted to try to code the (fairly simple) player state in C++, but I got stuck and was unable to find an example.

Here is the blueprint section, that grabs the playerstate array, and loops through them.

And here is the C++ code I have been experimenting with:

UE_LOG(LogTemp, Log, TEXT("[LEET] [AMyPlayerState] BroadcastChatMessage_Implementation - get game state "));
	AMyGameState* TheGameState = Cast<AMyGameState>(GetWorld()->GetGameState());
	UE_LOG(LogTemp, Log, TEXT("[LEET] [AMyPlayerState] BroadcastChatMessage_Implementation - get player array "));
	TArray<APlayerState *> player_array = TheGameState->PlayerArray;
	UE_LOG(LogTemp, Log, TEXT("[LEET] [AMyPlayerState] BroadcastChatMessage_Implementation - loop over player array "));
	for (int32 b = 0; b < player_array.Num(); b++)
		{
			UE_LOG(LogTemp, Log, TEXT("[LEET] [AMyPlayerState] PlayerState Found "));
			// Cast it back to our player state.  Right now it's just an array 
			AMyPlayerState* ThePlayerState = Cast<AMyPlayerState>(player_array[b]);
			// Convert string to text

			FText theText = FText::FromString(ThePlayerState->GetName());

			// Call recievemessage on the client
			ThePlayerState->ReceiveChatMessage(theText, ChatMessageIn);
		}

With this code, I see my logging up to “get player array”, then the server crashes.

Thanks for the assist!

I got this working by using the player controller iterator instead.