- Home /
How can I save the gold in my game scene to the main menu scene?
Hello I have a problem about PlayerPrefs. The golds in the game scene come to the main menu scene, but the previous golds are also deleted. For example; I won 5 gold from the first game, 5 gold will be written on the main menu scene. Let's say I won 4 gold in the second game, normally a total of 9 gold should be written on the main menu scene, but instead of deleting the previous gold, the gold I earned in the last game is written. So 4 will be written. How can I solve this problem? I need your help. I want all the gold to be collected in the main menu scene.
My game scene:
public class PlayerControl : MonoBehaviour
{
private float gold;
public Text goldText;
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.tag == "Gold")
{
goldText.text=((int)gold).ToString();
gold ++;
PlayerPrefs.SetFloat("Gold", gold);
PlayerPrefs.Save();
Destroy(collision.gameObject);
}
}
}
My main menu scene:
public class Menu : MonoBehaviour
{
public Text goldText;
public float gold;
void Start()
{
PlayerPrefs.SetFloat("Gold",PlayerPrefs.GetFloat("Gold") + gold);
gold=PlayerPrefs.GetFloat("Gold",gold);
goldText.text="Gold: " + gold;
}
Answer by Captain_Pineapple · Jul 18, 2021 at 02:26 PM
Well obviously you already write to the same player pref so you always overwrite previous values.
Unless you really want to save the gold count ever over a game restart i'd suggest you just use a static
variable to keep track of your gold. Static variables will be kept over scene changes.
for example:
public class GoldManager
{
public static int PlayerGoldCount = 0;
}
Then you can always just access and change the gold count with GoldManager.PlayerGoldCount ...
If you want to stick with your solution with the playerprefs you have to get
the player gold count and add the newly gotten gold count to the last count and then save
it again to the player prefs.
Your answer
Follow this Question
Related Questions
PlayerPrefs 2 Answers
PlayerPrefs don't load again after Android game closes for the first time. 1 Answer
There are wrong mathematical equations in PlayerPrefs. How can I resolve it? 1 Answer
how to save a load a game? 1 Answer
C# Issues with either PlayerPrefs.SetVariable or UnityEvent.Invoke 1 Answer