Home > Enterprise >  How to make a scene remeber an int value Unity
How to make a scene remeber an int value Unity

Time:07-22

I have a simple project. A button adds points one at a time to a counter. I then change the scene via another button and return to the original scene. The point counter has gone back to zero. How do i prevent this?

CodePudding user response:

Many ways to achieve this. But for starters you can save the number in Player Prefs.

"PlayerPrefs` is a class that stores Player preferences between game sessions. It can store string, float and integer values into the user’s platform registry"

So forexample this is your button callback function:

public void ButtonCallback()
{
    number  ;
    PlayerPrefs.SetInt("MyNumber", number);
}

To get the number next time you are in the scene, you can get the number using:

int number = PlayerPrefs.GetInt("MyNumber");

You will probably need to check if number exists in the first place when you launch the scene first time using:

PlayerPrefs.HasKey("MyNumber");

Read up more on this on: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

CodePudding user response:

Many ways to do this. In more detail, you can find this information on this answer.

  • Related