- Home /
PlayerPrefs resetting values on startup/restart?
Hi there. In my game I am using PlayerPrefs to store a currently available max health because I have health upgrades so I want the player to be able to keep those health upgrades each playthrough. The player will by default start with 3 "hearts" and then as they get upgrades, I am setting the "startHearts" value in playerprefs to be the upgraded amount, then retrieving that value on start up. But for some reason it keeps going back to "3" on start up even though I'm not setting it anywhere. It seems to favour the "Inspector's" value over the PlayerPrefs, because when I change the value in the inspector, it always starts with whatever I have in the inspector.
Here is my character tracker which checks for and sets the values on start up:
void Start()
{
if (PlayerPrefs.HasKey("UnlockedStartHearts"))
{
startHearts = PlayerPrefs.GetInt("UnlockedStartHearts");
currentHealth = PlayerPrefs.GetInt("UnlockedStartHearts") * 4;
currentMaxHealth = PlayerPrefs.GetInt("UnlockedStartHearts") * 4;
}
else
{
startHearts = 3;
currentHealth = 12;
currentMaxHealth = 12;
}
}
And here is my Player Health Controller which checks for then sets the values from the Character Tracker:
void Start()
{
currentMaxHealth = CharacterTracker.instance.currentMaxHealth;
currentHealth = CharacterTracker.instance.currentHealth;
startHearts = CharacterTracker.instance.startHearts;
PlayerPrefs.SetInt("UnlockedStartHearts", startHearts);
PlayerPrefs.Save();
Debug.Log("PPrefs 'start' StartHearts set:" + PlayerPrefs.GetInt("UnlockedStartHearts").ToString());
maxHealth = maxHearts * healthPerHeart;
CheckHealthAmount();
}
The PlayerHealthController accurately keeps the "start"hearts" and upgrades between levels, but then if I got back to the main menu and start a new game, it starts back at 3 (the value in the inspector) instead of the saved upgraded amount.
Is this only an issue while using the editor, and upon a build will work fine (I have not tried building and testing yet) because I know PlayerPrefs stores the values differently between the editor and the actual built game?
Confirmed; it does only do these when playing within the editor. A built version acts properly... So I don't know what to make of that. Haha.
Answer by PilgrimFlowers · Apr 27, 2021 at 11:47 PM
Also, here's the script for adding an upgrade, in case that also helps:
public void AddHeartContainer()
{
startHearts++;
startHearts = Mathf.Clamp(startHearts, 0, maxHearts);
currentHealth = startHearts * healthPerHeart;
currentMaxHealth = startHearts * healthPerHeart;
PlayerPrefs.SetInt("UnlockedStartHearts", startHearts);
PlayerPrefs.Save();
CharacterTracker.instance.startHearts = startHearts;
Debug.Log("PPrefs 'addheart' StartHearts set:" + PlayerPrefs.GetInt("UnlockedStartHearts").ToString());
CheckHealthAmount();
}