Saving and loading
There are some things to consider when you want to keep data in your scripts in order to stay compatible with loading save states (which also happens when using undo/redo). Whenever a save state is loaded, the entire scripting environment gets reset and all scripts are run again.
If you have any variables that may change over the course of playing the game, they will disappear when loading, and may be be re-initialized when your scripts run again. If you want to persist your variables, you need to use the setSavedData
and getSavedData
methods in GameWorld
and GameObject
.
These methods allow you to save a string for each object and for the whole game. The strings are stored in the save state, and you can retrieve them again after a state was loaded. The usual pattern would be calling setSavedData
whenever your state changes to make sure that whenever the game is saved, the string contains the latest information. Then, you call getSavedData
when you initialize your variables, check if saved data exists, and update your variables accordingly.
You can find a simple example of using saved data in the hit point counter in the UI tutorial. If you need to store multiple values, a convenient way is using JSON.stringify
and JSON.parse
to convert objects into strings. The advanced UI tutorial has an example for how this can be done.
The saved data needs to be sent across the network to all players. Even though scripts only run on the host, every player can save the current game state and load it later in a new game as host. In order to keep network traffic low and the gameplay smooth, try to minimize the size of your saved data strings, and only modify them when necessary.