Loading & Saving Game Sessions

Modified on Sun, 26 Dec 2021 at 10:02 AM

Loading/Saving game during playmode


Pressing Control + F4 will save your current game. The name for the file is set in Voxel Play Environment component (saveFilename property and defaults to "save0001").

The location of the saved game varies if the game is running inside Unity Editor or in a build. In Unity Editor, the game is saved to a folder under your World definition scriptableObject called "SavedGames". However in a build the saved games are stored in Application.persistentDataPath + "/VoxelPlay" folder.

Only modified chunks are included in the saved game file. 


Press Control + F3 to load the saved game from file (if you want to load a different file, then set the saveFilename property).


You can also save your game from the in-game console entering:

/save filename

/load filename



Savegame file format


The file format for all savegame files can be found here.



C# load/save methods


Voxel Play provides 4 C# methods to load / save your game world.

SaveGameBinary and LoadGameBinary works with external files, while SaveGameToByteArray and LoadGameFromByteArray works in memory which results in faster operations (useful for quick save/load).


- SaveGameBinary()

This method will gather the voxel data for all modified chunks (those with chunk.modified bit set to true) and save it to a file using the saveFilename property of VoxelPlayEnvironment component. The exported format is binary with RLE compression. The format is described here.

Important:


- LoadGameBinary(bool firstLoad, bool preservePlayerPosition)

This method is used to load a saved game from a file. The filename is specified by the saveFilename property and it's expected to be stored in the folder described above (see SaveGameBinary).

The firstLoad parameter is used to determine if the saved game is loaded during the game startup (ie. as a starting level) or if it's loaded amid an ongoing game (ie. the player loads a saved game).

The preservePlayerPosition parameter lets you specify if the current player position is preserved or if the location stored in the saved game will be used.


- SaveGameToByteArray()

This method exports the world data (pretty much like SaveGameBinary) but instead of writing to a file it returns the data as a byte[] array.


- LoadGameFromByteArray(byte[] saveGameData, bool preservePlayerPosition, bool clearScene)

This method loads a game from a byte array (ie. previously generated with SaveGameToByteArray).

The preservePlayerPosition specifies if the current player position should be preserved or not (if not, the location stored in the saved game will be used).

The clearScene parameter specifies if the entire scene should be cleared and regenerated. If set to false, only modified chunks will be replaced with the data from the saved game, which results in a faster load operation.




Save Custom Data


Voxel Play exposes two events that you can use to add or read custom data when the game is saved or loaded:


- OnSaveCustomGameData is an event that gets a CustomGameDataWriter object which is used to add any kind of data. For example:


VoxelPlayEnvironment.instance.OnSaveCustomGameData += MyCustomDataWriter;
...
void MyCustomDataWriter(SaveGameCustomDataWriter writer) {
    byte[] data = ...
    writer.Add("MY_DATA", data);
}


This way, whenever the game is saved, your event is called and you have the opportunity to add your custom data. The data is internally compressed using Deflate algorithm so the savegame file is kept as small as possible.


- OnLoadCustomGameData event is called when a savegame file is loaded. It gets a tag and a byte array with the contents of the custom section. The tag let you identify what kind of data is passed. For example:


VoxelPlayEnvironment.instance.OnLoadCustomGameData += MyCustomDataReader;
...
void MyCustomDataReader(string tag, byte[] data) {
   if (tag.equals("MY_DATA")) {
       // use the data
   }
}




Save GameObjects and custom data


GameObjects instantiated through a prefab can be included in the save game. To include a GameObject in the saved game, add the script "VoxelPlaySaveThis" to the prefab of that gameobject:



When the script is added to the prefab, the path to the prefab will be captured and saved in this component. Voxel Play will store the name, position, rotation and scale of any gameobject instantiated from this prefab when you save the game.

When the saved game is loaded, Voxel Play will instantiate the prefab (once per gameobject saved) and restore the name, position, rotation and scale of the gameobjects.


Custom data can also be saved. When a game is saved, any gameobject with the VoxelPlaySaveThis attached receives a OnSaveGame event which you may use to store custom data. Likewise, when the game is loaded, the VoxelPlaySaveThis gameobject receives the OnLoadGame event with the custom data passed as a parameter so you can read the data and initialize your own scripts accordingly.


The follow script uses the OnSaveGame and OnLoadGame to support saving custom attributes in a savegame. Note: any script that uses these events must be attached to the prefab which must also contains the VoxelPlaySaveThis script:


using System.Collections.Generic;
using UnityEngine;
using System.Globalization;


namespace VoxelPlay
{


    public class DeerData : MonoBehaviour
    {


        public string animal = "Deer";
        public int hitPoints = 20;


        public void OnSaveGame (Dictionary<string, string> data)
        {
            data ["Animal"] = animal;
            data ["HitPoints"] = hitPoints.ToString (CultureInfo.InvariantCulture);
        }


        public void OnLoadGame (Dictionary<string, string> data)
        {
            data.TryGetValue ("Animal", out animal);
            string s;
            data.TryGetValue ("HitPoints", out s);
            int.TryParse (s, out hitPoints);
        }
    }
}


Demo scene 1 contains an example of this functionality. Run the demo and press "Y" to instantiate a Deer prefab. Select the instantiated Deer gameobject and notice it contains a VoxelPlaySaveThis script and a DeerData script. You can move the Deer around or change the animal or hitPoints properties. Save the game and load it. The Deer will appear where it was when the game was saved and the custom data is preserved.




Save custom data on individual voxels


Voxel Play also allows you to store data on individual voxels. This data gets also saved into the savegame file. Check this page for more details.





Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article