Sunday, June 22, 2014

[libgdx]day 13 – settings

We already have a cool options menu (with more or less sencefull options), but the settings we change there aren’t saved yet.
In libgdx therefore there is the class Preferences. We give our TestGame an object of this class, so that we can access it from everywhere.
In our LoadingScreen we then create the object:
// load options
game.preferences=Gdx.app.getPreferences("settings");
“settings” is the name of our preferences. We could store different bundles of preferences, if we want for example have one bundle for our settings and one for the highscores.
Every preference consists of a key and a value. If we ask for a specific value via it’s key (e.g. “volume”) we can as well pass a default value for the case that this preference is not set yet.

volume=game.preferences.getInteger("volume",100);
Nearly the same way we can change these settings in our OptionScreen.
game.preferences.putInteger("volume", volume);
They aren’t really saved yet. To save them we have to flush them.
game.preferences.flush();
Of course we are not only able to save key-value preferences, but as well normal files.
android can save files locally or externally (on the sd-card). (for external save you need a permission. like in the previous tutorial).
On the desktop the local files are stored relative to the workspace and the external files relative to the home-folder.
First you should check, if the storages are avaiable.
boolean externalAvailable = Gdx.files.isExternalStorageAvailable();
boolean localAvailable = Gdx.files.isLocalStorageAvailable();
Now we need a FileHandle to access the files.
FileHandle externalFile = Gdx.files.external("myfile.txt");
FileHandle localFile = Gdx.files.local("myfile.txt");
Reading and writing files is even easier than in pure Java.
String contents = file.readString(); // read
file.writeString(contents, false); // overwrite
file.writeString(new_stuff, true); // append
More infos on handling files you find in the documentation.
At the moment I have no idea, what I’m going to do tomorrow. Sadlywise I have to do stuff for school parallel, so I do not yet know how to do collisions.

No comments:

Post a Comment

Popular Posts