- Home /
Having multiple save files
Hey there, I was wondering if there was an easy way to have multiple characters with their own save slot. I tried this and was able to create 4 slots, each saved their own playerprefs with a name ("Slot1-Name: Steve"), and this worked alright at the beginning, but later On I found that if I try to use any variable that another save slot has stored it will also change that slave slot as well. With this method it looks like I'll just have to create the same game 4 times over just for it work.
I'm somewhat willing to do that but it just seems so inefficient, is there any other way to do this?
Answer by aldonaletto · Apr 27, 2012 at 01:02 AM
You can save the variables prefixed with the slot or user name - for instance:
PlayerPrefs.SetFloat(userName+":Health", health);
PlayerPrefs.SetInt(userName+":HasRifle", hasRifle?1:0);
PlayerPrefs.SetInt(userName+":CurLevel", Application.loadedLevel);
To keep track of the users, you could save a NumUsers value and the user names as User1, User2 etc. - read NumUsers first, allocate the user names array and load them:
var numUsers: int; var userNames: String[];
function Start(){ numUsers = PlayerPrefs.GetInt("NumUsers", 0); userNames = new String[numUsers]; for (var i = 0; i < numUsers; i++){ userNames[i] = PlayerPrefs.GetString("User"+i.ToString()); } } When registering a new user, save it using the current numUsers as the index, increment numUsers and save it too:
PlayerPrefs.SetString("User"+numUsers.ToString(), newUserName); numUsers++; PlayerPrefs.SetInt("NumUsers", numUsers); // update the PlayerPrefs file to avoid data loss case the game or computer crashes PlayerPrefs.Save();
Your answer
