Super Static - saving variables between game sessions
- NerdHead
- Sep 15, 2021
- 1 min read
You probably know about PlayerPrefs to save and get date between game session in your unity game.
But using and calling functions in your game all the time make the code harder to read and manage.
And the worse part it using string for the name, I cant count the times something changed and I worked so hard just to find out that the name changed...
Why am I Whining about this?
Because
There is a better way to do it
Let's start with the functions we all already use:
void SetIntPrefs(string name, int newValue)
{
PlayerPrefs.SetInt(name, newValue);
}
int GetIntPrefs(string name)
{
return PlayerPrefs.GetInt(name, 0);
}Now we make one small thing that will change the way we use PlayerPrefs in our code.
Let's declare a variable with get and set that are calling our functions:
public int highScore
{
get { return GetBoolPrefs(nameof(highScore)); }
set { SetBoolPrefs(nameof(highScore), value); }
}* Notice that we are using nameof the variable so when we change the variable name everything will change together and we can avoid some unnecessary bugs easily.
Note:
This method is best used in varibales that are called once in a while and usually are called together with the PlayerPrefs functions (like high score, player name, sound manager settings and more).
The full code
public int highScore
{
get { return GetBoolPrefs(nameof(highScore)); }
set { SetBoolPrefs(nameof(highScore), value); }
}
void SetIntPrefs(string name, int newValue)
{
PlayerPrefs.SetInt(name, newValue);
}
int GetIntPrefs(string name)
{
return PlayerPrefs.GetInt(name, 0);
}