Variable won't save when exiting the game and will not increment.
I have a variable gem_number with gets from another script (also the game object is in a different scene) a number. I am trying to add the number to trueGems variable, display it on the screen and save the number when exiting the game. The problems are: the gems don't save when exiting the game and reset when reentering in this scene instead of adding new value.
using UnityEngine;
public class Gem_show : MonoBehaviour
{
public TMPro.TextMeshProUGUI Gems;
public static int gem_number; //get the number of gems earned
private int trueGems; //the total of gems stored
private void Start()
{
trueGems += gem_number; //add to the current gems more gems
PlayerPrefs.SetInt("Gem", trueGems); //don't lose the gems when exit the game
Gems.text =PlayerPrefs.GetInt("Gem").ToString(); //display gems
}
Answer by Bunny83 · Aug 26, 2021 at 09:53 AM
Well, your logic doesn't make much sense. It also means you haven't really debugged your code (which is just 3 lines). When your game starts, what do you think that your "trueGems" variable contains? Right, the value 0. When this script is created and Start is executed, you add get_number to 0 and store it in your playerprefs. Don't you think it would be a good idea, now that you did all the efford of storing the value from your variable into the player preferences, to actually load the value back at some time? Specifically
private void Start()
{
trueGems = PlayerPrefs.GetInt("Gem", 0); // load the last value from player prefs, or 0 if not found
trueGems += gem_number; //add to the current gems more gems
PlayerPrefs.SetInt("Gem", trueGems); //don't lose the gems when exit the game
Gems.text = trueGems.ToString(); //display gems
}
Your answer
