- Home /
PlayerPref resets the value,PlayerPref displays the stored value and then resets it
Hi, so I was trying to learn PlayerPrefs and so I built a simple counter that increments the count when clicked and saves it. The next time when you start the counter it starts the count where you had left.
However, in my case, if you have stopped the count at 6 and then you want to start again the next count will be 7 but the one after that again starts with 1 and so on. Any help is appreciated.
Script:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class CountText : MonoBehaviour {
public Text countText;
public int count;
public void TextChange()
{
count++;
}
public void SaveData()
{
PlayerPrefs.SetInt("count", count);
}
public void LoadData()
{
print(PlayerPrefs.GetInt("count"));
countText.text = PlayerPrefs.GetInt("count").ToString();
}
}
[1]: /storage/temp/165137-screenshot-2020-08-10-at-114157-am.png
Answer by DialBlitzness · Aug 10, 2020 at 06:42 AM
Hello !
It seems to me that when you load the data, you just fill in countText.text with the saved value, but that the count variable is not updated so far, and starts from the beginning. You are missing a line in LoadData (), like:
public void LoadData()
{
print(PlayerPrefs.GetInt("count"));
count = PlayerPrefs.GetInt("count")
countText.text = count.ToString();
}
Hi, I tried this but now, the count doesn't change. If it's at 6 it stays at 6
This part should work, I think the error is somewhere else. Do you have other things to show us? Where do you call TextChange () for example?
This is all. I have a button and a text element. TextChange() gets called when the button is pressed. Same goes for LoadData() and SaveData()
Your answer
Follow this Question
Related Questions
options menu UI doesnt save when switching scenes 1 Answer
How to make my game settings save? 1 Answer
Load And Saving player prefs -1 Answers
PlayerPrefs file wrong stored location 0 Answers