Citrus
Citrus

Reputation: 41

Unity PlayerPrefs Issue

I'm developing a clicker style Android game and i have come to a place where I need to save data using PlayerPrefs for obvious reasons. However, I have run into a problem I can not seem to find. I can't find the error and i have looked for a couple of hours. In the game upgrades are purchasable. And some of them multiple times. There is a variable that saves the number of times the upgrade has been purchased and it is stored into PlayerPrefs. From another script, I'm actually checking the data and set things as they should be using a switch. Here's the code itself:

Shop item code where I save the PlayerPref:

public void fasten()
{
    if(clickScript.clickCount>=tenPercentPrice && numberOfTimesUsed<5)
    {
        overTimeScript.waitTime-=0.1f;
        clickScript.clickCount=clickScript.clickCount-tenPercentPrice;
        tenPercentPrice=tenPercentPrice*4;
        numberOfTimesUsed++;
        PlayerPrefs.SetInt("numberOfTimesFasten",numberOfTimesUsed);
    }
}

Code which is supposed to load it:

void Start()
{
    int fastenNumber = PlayerPrefs.GetInt("numberOfTimesFasten",0);   

    switch(fastenNumber)
    {
        case 0:
            break;
        case 1:
            overTimeScript.waitTime-=0.1f;
            shopScripts.tenPercentPrice*=4;
            break;
        case 2:
            overTimeScript.waitTime-=0.2f;
            shopScripts.tenPercentPrice*=80;
            break;
        case 3:
            overTimeScript.waitTime-=0.3f;
            shopScripts.tenPercentPrice*=320;
            break;
        case 4:
            overTimeScript.waitTime-=0.4f;
            tenPercentPriceText.GetComponent<TMPro.TextMeshProUGUI>().text="MAX";
            break;
    }

Thank you in advance to anyone that takes a look at this and tries to help.

Upvotes: 1

Views: 1496

Answers (2)

JustAMissionary
JustAMissionary

Reputation: 41

PlayerPrefs is the worst place to store important game save data. That's the first place I would look if I wanted to hack the game. Although I would probably try a memory hack first.

If you're going to store it there, at least come up with some kind of encryption for the name of the variable and the variable value.

Upvotes: 1

derHugo
derHugo

Reputation: 90679

After PlayerPrefs.SetInt you should do PlayerPrefs.Save otherwise the PlayerPrefs are not saved until OnApplicationQuit when the app is closed.

By default Unity writes preferences to disk during OnApplicationQuit(). In cases when the game crashes or otherwise prematuraly exits, you might want to write the PlayerPrefs at sensible 'checkpoints' in your game.

This means if you are trying to PlayerPrefs.GetInt in the same session without having called PlayerPrefs.Save you will always get the value from the previous session.

Upvotes: 2

Related Questions