M
M
MrPipka2022-01-05 14:04:33
Unity
MrPipka, 2022-01-05 14:04:33

Autosave variables in Unity?

In general, I'm creating a clicker game and ran into a problem. I wrote autosave and everything seems to be fine, but when the game starts, all variables are reset to zero.

I have 6 variables and each has a value, but when they start they are all reset (clickolus = 1, and when you start clickolus = 0 for some reason)

Variables:

public int clicks;
    public int clickolus;
    public int costonee;
    public int costupdonee;

    public int costtwoo;
    public int costupdtwoo;


void start
void Start()
    {
        clicks = PlayerPrefs.GetInt("clicks");
        clickolus = PlayerPrefs.GetInt("clickolus");
        costonee = PlayerPrefs.GetInt("costonee");
        costupdonee = PlayerPrefs.GetInt("costupdonee");
        costtwoo = PlayerPrefs.GetInt("costtwoo");
        costupdtwoo = PlayerPrefs.GetInt("costupdtwoo");
    }


void update
void Update()
    {
        moneytext.text = clicks.ToString();
        moneytext.text = "" + clicks;

        costonetxt.text = costonee.ToString();
        costonetxt.text = "Цена: " + costonee;

        costtwotxt.text = costtwoo.ToString();
        costtwotxt.text = "Цена: " + costtwoo;

        PlayerPrefs.SetInt("clicks", clicks);
        PlayerPrefs.SetInt("clickolus", clickolus);
        PlayerPrefs.SetInt("costonee", costonee);
        PlayerPrefs.SetInt("costupdonee", costupdonee);
        PlayerPrefs.SetInt("costtwoo", costtwoo);
        PlayerPrefs.SetInt("costupdtwoo", costupdtwoo);
    }


Hope for help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
freeExec, 2022-01-05
@freeExec

1. Call PlayerPrefs.Save()
2. Don't use PlayerPrefs in Update

L
LittleBob, 2022-01-05
@LittleBob

After all PlayerPrefs write PlayerPrefs.Save();
It's also not a good idea to save in Update, it's better to save on click

M
mustGamedev, 2022-01-05
@mustGamedev

Everything is reset from your saves because you reset everything in Update in the first lines because it is called every frame.
Don't listen to playerPrefs.Save(); - it won't give you anything. This function is always executed automatically after the application closes.
To begin with, we read the documentation on playerprefs, then we ask questions.
So that the values ​​​​are not reset, think about what is wrong with you at the beginning of Update

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question