Sharing data between screens
In many games, you often need to share data between different screens. For example, you may want to keep track of the player's score, inventory, or settings, and access it on multiple screens.
The Saxion GameApp provides a built-in key-value store that allows you to store objects and retrieve them from anywhere in your game. This store is simple to use: you can add items, get items, and remove items as needed.
Add an Item
You can add any object type to the key-value store. In the following examples we are going to use the following Configuration class.
Let's create an instance of the configuration and save it to the item store, under the name "config".
Configuration configObject = new Configuration();
configObject.musicEnabled = false;
configObject.soundsEnabled = true;
GameApp.addItemToStore("config", configObject);
Get an item
Retrieves an object from the store. We will need to cast it to the correct type.
@Override
public void show() {
Configuration config = (Configuration) GameApp.getItemFromStore("config");
}
Remove an item
Removes an item from the store.
Checking if an item exists
Sometimes you may want to check if a specific key exists in the store before trying to get it. You can use the hasItemInStore method:
if (GameApp.hasItemInStore("config")) {
Configuration config = (Configuration) GameApp.getItemFromStore("config");
} else {
System.out.println("No configuration found in the store.");
}
Notes
- Keys are case-insensitive, so "Config" and "config" are treated the same.
- The store is shared across all screens, so you can use it to pass data between screens easily.
- Always cast the object to the expected type when retrieving it.