- Home /
PlayerPrefs. Adding multiple strings on a List and saving it on PlayerPrefs.
Hello guys, I really need your help. I'm stuck. I'm saving my string to PlayerPrefs but the strings on index 3 will overwrite and causes Out of Range error when I'm saving it again. Here's my code.(Updated)
private void BallSkinSave()
{
if (PlayerPrefs.HasKey("skinCount"))
{
Debug.Log("already exist " + skinCount);
getSkinCount = PlayerPrefs.GetInt("skinCount");
getSkinCount++;
PlayerPrefs.SetInt("skinCount", getSkinCount);
for (int i = 0; i < getSkinCount; i++)
{
mySkins.Add(skinObject.gameObject.name);
PlayerPrefs.SetString("skinCollections" + (getSkinCount -1), mySkins[i+(getSkinCount - 1)]);
}
getSkinCount++;
}
else
{
Debug.Log("first time buying");
skinCount++;
mySkins.Add(skinObject.gameObject.name);
PlayerPrefs.SetInt("skinCount", skinCount);
PlayerPrefs.SetString("skinCollections" + 0, mySkins[0]);
}
PlayerPrefs.Save();
}
I'm almost close to done. The problem left now is that my int i is set to 1 when there are no values. Please help. Anything is appreciated, Thanks in Advance,
Update: This still doesn't work. Even if 1 session only since mySkins[i] doesn't have any values yet.
Why don't you just use a dictionary with key skinIndex and value the skinName ins$$anonymous$$d of indexing on the collection?
I don't understand the for loop, why do u wanna add duplicates of the same skin into your mySkins list?
It should just be as easy as
public List<string> objectIDs;
private const string objectIDHash = "objID";
public void SaveIDs()
{
for (int i = 0; i < objectIDs.Count; i++)
{
PlayerPrefs.SetString(objectIDHash + i.ToString(), objectIDs[i]);
}
PlayerPrefs.SetInt(objectIDHash, objectIDs.Count);
}
public List<string> GetIDs()
{
List<string> loadedIDs = new List<string>();
for (int i = 0; i < PlayerPrefs.GetInt(objectIDHash); i++)
{
loadedIDs.Add(PlayerPrefs.GetString(objectIDHash + i.ToString()));
}
return loadedIDs;
}
Answer by Tsaras · Mar 04, 2019 at 08:03 PM
It is hard to understand exactly what you want to do with your code, but I can see some immediate flaws:
for (int i = 1; i < getSkinCount; i++)
{
mySkins.Add(skinObject.gameObject.name);
PlayerPrefs.SetString("skinCollections" + (getSkinCount - 1), mySkins[i]);
}
Why are you starting the iteration at i=1 and not 0? And also what you do in the loop is overwriting the value of string "skinCollections" + (getSkinCount - 1) which is constant throughout the looping with mySkins[i].