Towards a generalized solution
The current saving and loading system will not work consistently as we add new features to the game
To generalize further we need to split saving into two parts - marked for saving and saved
Then split loading into two parts pre-load check and loading
Create Custom Resource for our saved data
Create a New Script called saved_data.gd
Set the class_name to SavedData
create variables to store
the position and the scene_path
Update the SavedGame Resource script
remove the strawberry positions
add an array of saved data
Every node that wants to save itself
needs an on_save_game function
This is the function implemented in the Strawberry script
Add each node that needs to be saved
to a new group called save
Return to the SaveAndLoad script
In the save_game function
Create a list of data about the object to save
now call the on_save_game function in all nodes which are in the save group and send the list of data as a parameter
Finally push the saved data into the new field in the SavedGame resource
Any node which needs to complete operations
BEFORE loading the game must have a
on_before_load_game() function
add the on_before_load_game() function
remove the strawberry from its parent
delete the strawberry from the scene
In the SaveAndLoad script
replace with a call to the save group
Now restore the saved items
by looping through the array
and add it to the current scene
finally restore the internal values
of each node by calling the new
Create the on_load_game function
in all nodes which need to be loaded
This save system works well however it exposes some vulnerabilities/ Because the save data is stored in an external and human-readable format cheaters could manipulate values such as health or high score etc.
A more serious issue is that malicious code can be injected into our save files which will run when we load a game.
To prevent this you can install an addon from the asset library to check save files for malicious code before loading it
Go to the asset library and search for the keyword "safe"
Choose the Godot Safe Resource Loader by dekork
Add the plugin to the project
Click on Project --> Project Settings --> Plugins
Project --> Reload Current Project
go to the SaveAndLoad script
go to the load_game function
the plugin contains a SafeResourceLoader class
use this to load the save file
Add a check to print a message if