Playerprefs saving coins

Hey guys!

I have two scenes the “game” scene and the “menu” scene. In the game scene I have the coins score which increases when you collect a coin. Then I used Playerprefs in order to save the collected coins when I die.

Now when I’m in the menu scene I want my total coin a,mount displayed, but when I use playerprefs in order to get the coins from the last game it updates every time so it only shows the coins I collected during the last game!

How can I fix this? Thankful for every response!

this is the game scene method to save the coin score

public void OnDeath()
    {

        deadCointext.text = coinScore.ToString() + "x";
        PlayerPrefs.SetInt ("coins", coinScore);



    }

this is the menu scene weher I want to have all the coins ever collected

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class mainmenu : MonoBehaviour {

    public Text highscoreText;
    public int currencyInRun;
    public Text coinsScore;



    // Use this for initialization
    void Start () {
        highscoreText.text = "HIGHSCORE:" +  ((int)PlayerPrefs.GetFloat ("Highscore")).ToString();

        currencyInRun = PlayerPrefs.GetInt ("coins");


        coinsScore.text = "" + currencyInRun;

    }
}

You are setting the coins to be equal to the current game’s coins. Obviously you will get the last game coins. What you wanna do is ADD the current game coins to the existing amount of coins.
Something like :

coins = PlayerPrefs.GetInt("Coins", coins); //The old amount of coins
PlayerPrefs.SetInt("Coins", coins + coinsScore); //The new amount of coins, aka the old amount of coins + the current game amount of coins.
PlayerPrefs.Save();

but where should I put this, in which script? and I don’t think that yours is working, because it saves the coins and in the next one it gets the saved coins plus the new one, but the saved coins and the new ones are the same in this case. Or am I wrong?

Guys anyone has an idea? Pleaseeee

My code is not wrong but I’ll try to make it even simpler…

int coins;
int thisGameCoins;

void Start()
{
coins = PlayerPrefs.GetInt("Coins", 0); //Here we are getting the amount of coins. By default, the first time you play, it will be 0.
}
public void IncreaseCoin()
{
thisGameCoins += 1; //Whatever you do to get a coin.
}
public void GameOver()
{
PlayerPrefs.SetInt("Coins", coins + thisGameCoins); //Here we are setting (saving) the coins to be sum of the old coins + the new coins!
PlayerPrefs.Save();
}
1 Like

You have the right idea, but you could move line 6 to be just before line 14, and then you don’t need a member variable to hold the old coins all the time.

I wouldn’t use player pref at all for coins. That’s sloppy and easy to cheat. I would suggest serialization

I’ll post my scripts tomorrow for you. Very easy to use.

1 Like

Yea I read that you can just overwrite the score when using playerprefs, but I’m a noob so I don’t really know how to use something else than playerprefs! It would be awsome if you could post it!:slight_smile:

Ok so the first on is your Game script. This holds all your variables like ints, floats, Etc.

using System.Collections;
using System.Collection.Generic;
using UnityEngine;

[System.Serializable]

public class Game
{

public static Game current = new Game();
public int _gold;

}

The second one does the serialization. Its called SaveLoad.

using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class SaveLoad
{

    public static void SaveGame()
    {
        BinaryFormatter bf = new BinaryFormatter();
        if (File.Exists(Application.persistentDataPath + "/SavedGame.dat"))
        {

            FileStream file = File.Open(Application.persistentDataPath + "/SavedGame.dat", FileMode.Open);
            Game game = new Game();
         
            game.Gold = Game.current.Gold;// Add your items from Game like this. Remember to do game.Gold for this section.

            bf.Serialize(file, Game.current);
            file.Close();
        }
        else
        {

            FileStream file = File.Create(Application.persistentDataPath + "/SavedGame.dat");
            Game game = new Game();
          
            game.Gold = Game.current.Gold; // Add your items from Game like this. Remember to do game.Gold for this section.

            bf.Serialize(file, Game.current);
        }


    }

    public static void LoadGame()
    {
        if (File.Exists(Application.persistentDataPath + "/SavedGame.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/SavedGame.dat", FileMode.Open);
            Game game = (Game)bf.Deserialize(file);
            file.Close();

            Game.current.Gold = game.Gold;// Add your items from Game like this. Remember to do Game.current.Gold for this section.
         


            Debug.Log("Loaded The File");
        }
        else
        {
            Debug.Log("File Does Not Exist");
        }
    }
}

So when ever you wanna add to your gold or score you would just add to the gold int.

Game.current.Gold ++;

And then you wanna make sure that you save this when ever your wanting to save gold amount. That way when the user re opens your game they have their gold saved. You can do this for high score saving also. But if your using this for score solely then you want to just say in start function

Game.current.Gold =0;

And then you can pull that to use in your score UI.

To save it

SaveLoad.SaveGame();

And then load the file at the beginning of the scene where your score is held

SaveLoad.LoadGame();
1 Like

Wow thank you so much! I’ll try it!

Np. Let me know if you have any questions about it.

Okay I tried to implement it into my game, but I’m not quite sure where to put all that…

it worked!

1 Like

Hey mate!!! I am new to Unity. What did you do to make it work?

Definitely start with some tutorials.

7152541--856066--Screen Shot 2021-05-18 at 8.50.46 AM.jpg

When you get stuck, PLEASE start your own post according to forum rules.

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

How to understand compiler and other errors and even fix them yourself:

https://forum.unity.com/threads/assets-mouselook-cs-29-62-error-cs1003-syntax-error-expected.1039702/#post-6730855

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379