Using preferences to store game states and options
Being able to read and write both text and binary files in your Libgdx projects already gives you all the flexibility you will ever require to handle game saves and configuration files. However, binary files might not be very convenient to store key-value pairs.
Do not worry! Libgdx always keeps a hidden ace. If all you need is to store a set of key-value pairs to keep track of basic player progress or game settings, there is a small utility that will make your day. The Preferences
class offers an extremely simple API for you to store things such as top scores, the desired music volume, and so on.
This brief recipe will show you how to use this utility to your advantage.
Getting ready
Very quickly, import the samples projects into your Eclipse workspace.
How to do it…
Every Preferences
instance points to an internal file. Creating or loading an existing file is as easy as calling the getPreferences()
method in the Application
interface:
Preferences...