Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

Saving data

Before working on the sounds, I still have few things to do, in order to have a game fully playable :

  1. Saving data : For this game we'll only save the number of levels we completed, so we won't need to start the game from start every time we play.
  2. Create a level selection screen

Saving data

Storing and loading small data, like a level number, is very easy in libGDX with the Preferences.

Firs, let's create the Data.java :

public class Data {
    
    public static Preferences prefs;
    
    public static void Load(){
        prefs = Gdx.app.getPreferences("Data");
        
        if (!prefs.contains("Level")) {
            prefs.putInteger("Level", 1);
        }
    }
    
    public static void setLevel(int val) {
        prefs.putInteger("Level", val);
        prefs.flush();                            //Mandatory to save the data
    }

    public static int getLevel() {
        return prefs.getInteger("Level");
    }
}

In the Load() function, we check if the field "Level" exits. If not, we create it and attribute it a default value. Then, in the game we can access to this value with the getLevel() function and we can modify its value with the setLevel() function.

Loading the data

Before accessing the data "Level", we need to load the Preference file. We'll do that in the main activity, MyGdxGame.java, simply by using this line in the create() :

Data.Load();

Accessing the data

Then, when we need to know which level we unlocked, we can access to this number with the line :

Data.getLevel();

Saving data

At the end of a level, when we want to increment the number of the level we unlocked we only need to do :

Data.setLevel(Data.getLevel()++);

You can skip the checking for level and then setting it, if it's not available. Instead you can (where you access it) give a default value, if it's not in the prefs:

prefs.getInteger("Level", 1);

I know it just saves two lines - but the more values you save, the easier it makes your life :)

Thanks for the tip ! ;)