top of page

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);
}
 
 

Recent Posts

See All

FAVORITES

Try playing Core Keeper and learn from it's sound design!

From the sound effect to the music - this is a masterpiece!

WHAT'S NEW?

New game on Steam and a new mobile video asset are soon to be published!!

I AM THINKING ABOUT

AI is on the rise. Being able to use it in the right cases and explaining the task correctly is no easy task but once you finish a full task without writing a line of code - your world will change!

CONTACT ME

Use any social media to contact me. For any question about programing and project I prefer using my Discord server, See you there!

© 2021 by Amit Klein. Nerd Head.

bottom of page