I don't know about anyone else out there, but understanding PlayerPrefs and arrays has me to the point of giving up! There is very little documentation on something seemingly critical to web play! YES, I've looked at the wiki ArrayPrefs, but I cannot understand it and when I attempt to copy/paste and retrofit, I get overload errors. With that said, I realize those examples are VERY simple, but for some maybe not so simple. For those who find it simple I would hope you would remember that UnityAnswers is for EVERYONE and that includes those who may not be near your level of expertise and require a little more info. So; with that out of the way, are there any simpathetic souls who can assist? I know PlayerPrefs for single pieces of info. What I need is how to create a PlayerPref with a single user, then add to that file with additional players/scores, then read back the file for future play.
1 Answer
1What you can do is have each player data prefix or suffix with a player index.
For example, if players have this data associated:
- Name
- Health
- Score
You could then support several player profiles as such:
- Name0
- Health0
- Score0
- Name1
- Health1
- Score1
- Name2
- Health2
- Score2
And you could keep track of how many players there are with another key
- PlayerCount
To select the name for player 1, you could do something like this:
var playerName : String = GetPlayerName(1);
function GetPlayerName(playerIndex : int) : String
{
var key : String = IndexedKey("Name", playerIndex);
return PlayerPrefs.GetString(key);
}
function IndexedKey(key : String, index : int) : String
{
return String.Format("{0}{1}", key, index);
}
Note that you will need to move up entries if a player is deleted. For example, deleting player 1 needs all player 2 data to be stored in player 1 slots, and all player 3 data in player 2 slots, and so on. Otherwise you'll get "gaps" that you might have a hard time solving.
– StatementEdit: Fixed typo in script.
– StatementString.Format only formats a string. That is, it produces a string like "Name1". Then we use that string to be the key, that is used to access the data in player prefs. So we're calling PlayerPrefs.GetString("Name1"); basically. If you are willing to go one step further and make classes to help you maintain your data, you can make this completely transparent. Do you prefer C# or JS code? I could cook up a complete example.
– StatementYou could just use another key that describes how many players exist. If you add a new player, then increment that value.
– StatementIt'll take some while. I am more of a C# guy and have a hard time going about in JS :) But it's good practice for me as well.
– Statement