Search Unity

  1. Are you interested in providing feedback directly to Unity teams? Sign up to become a member of Unity Pulse, our new product feedback and research community.
    Dismiss Notice

PlayerPrefs Use in Multiplayer Game

Discussion in 'Scripting' started by QuickiSticki, May 7, 2021.

  1. QuickiSticki


    Nov 18, 2020
    Hey, everyone!

    I made a fairly simple multiplayer game. At the start of the game, before you load into any server, you select the character you want to play as. Currently, I have this selection saves as a PlayerPref. When the scene then changes and loads the map, you are given the saved PlayerPref int for the character you selected.

    Here lies my issue. When another player joins my game, they also select a player, which gets saved as a PlayerPref int, and then they load into the game. When they enter the map, their new PlayerPref int is given to every player, giving every player the same selected character, not the characters that they chose individually.

    So, can I separate each persons PlayerPref int so that it is only read by their local game, not by the server or other players? If not, what would be a good, easy way to save and load this same information? The only info that I want to save at all in this game is the selected character and the selected game settings in the options menu.

    Thanks for any advice!

    NOTE: If PlayerPrefs are saved locally, is this only happening because I am playing both instances of the game on the same computer?
    Last edited: May 7, 2021
  2. Kurt-Dekker


    Mar 16, 2013
    With multiplayer I'm not sure where you want to keep the authoritative truth about who chose what, but basically you just need more than one integer, and it's kind of up to you how to implement it.

    Cheapest is to just make a dynamic PlayerPrefs key such as "PlayerX" where X is replaced by 0,1,2,3, etc as each player is stacked in the lobby.

    Obviously you would need to ensure that player X is called the same X on everybody's machine, and I'm not sure what facilities there are in Unity multiplayer these days.

    You could also use something else unique about the player such as their IP address (if you can get it) or their name, and use that as the PlayerPrefs key.

    The ultimate solution would be to have a game configuration structure that contains EVERYTHING you will ever need going into the game, such as player skin choice and anything else your lobby might let players set, like class, equipment, etc.

    And these quantities would need to be synced of course, by whatever syncing method you're using.
    Joe-Censored likes this.
  3. Joe-Censored


    Mar 26, 2013
    Why even use PlayerPrefs for this? PlayerPrefs are generally for saving data between different runs of the game, not for saving data between scenes of the same run of the game. Use static variables, or a DontDestroyOnLoad object, to move data between scene loads.