In my game, players need to choose a Hero before entering the level. Apparently, UGameInstance is where I should “save” the character selection before I open the game level.
In local multiplayer, no problem as all human players share the same computer, hence the same game instance.
But in network multiplayer, each connected client has its own UGameInstance.
What’s the correct way of storing the selected hero for each client, since the game instance is not replicated accross the network?
Still use GameInstance, but after the map is loaded, I fill each PlayerState on the server with the infos found on the gameinstance, and in OnRep_PlayerState I load the correct skeletal mesh, and so on?
What’s the preferred way of doing this? (Preferably a cross local/network multiplayer way :p)
As far as I know, yes, this would be the correct way to do that, a quick breakdown would be something like follows:
Player 1 hosts a lobby
Player 2 connects to the lobby
Player 1 selects a character, and that selection is saved on the host’s GameInstance
Player 2 selects a character, and sends it’s selection via Server-RPC to the host
The host generates a unique ID for the player, and saves the player’s selection together with that unique ID
The host sends the generated ID back to Player 2
Player 2 saves the ID on his local GameInstance
The host (Player 1) initiates a ServerTravel to the actual game map
Player 1 can read his character selection directly from his game instance upon loading
Player 2 notifies the host (Player 1) when he finished loading, and sends his locally saved ID and PlayerController along
The server (Player 1) performs a look-up in his GameInstance with the provided ID, and spawns the saved character for the PlayerController that was sent along
This can easily be extended for an arbitrary amount of clients. Sadly, this does feel very clunky to do, but (at least to my knowledge) there is no better option for transferring such data between maps (except using seamless travel, which doesn’t seem to be useful when transitioning from a Lobby to an in-game map).
One last note: If you use a TMap in the GameInstance to store the ID together with the character selection, you can wrap the character selection into a USTRUCT. This way you can easily extend the system to save more than only the character selection from each client (for example team selections, maybe color selections or whatever else a player might select in the lobby).