Creating a Save File

We know that you can create a save file using the Save File Setup component. Alternatively, you can create a save file through code.

Unencrypted Save

A save file needs save file setup data to be created. The code below creates save file setup data.

SaveFileSetupData saveFileSetupData = new SaveFileSetupData()
{
    fileName = "Save File",
    saveLocation = SaveLocation.PersistentDataPath,
    filePath = "Example/Path", // The path AFTER the persistent data path (can be left empty)
    fileType = FileType.Json,
    encryptionMethod = EncryptionMethod.None,
    addToStorage = true
};

SaveFile saveFile = new SaveFile(saveFileSetupData);

However, this code will not create an encrypted save file.

Encrypted Save

The only supported encryption method at the time was AES. To create an AES-encrypted save file, we would need an AES key and IV. These are used for the AES algorithm. Both the AES key and IV are just a string of random alphanumeric characters. It is recommended that they be at least 16 characters in length.

1. Store the AES Key and IV

The key and IV of a save file must not change, as the same key and IV are required during both encryption and decryption. So, we should create constants that we will use every time.

private const string aesKey = "randomkey1234567";
private const string aesIV = "randomiv12345678";

2. Create Setup Data

This will be similar to the previous one, except we will change the encryption method to AES and provide the key and IV.

SaveFileSetupData saveFileSetupData = new SaveFileSetupData()
{
    fileName = "Save File",
    saveLocation = SaveLocation.PersistentDataPath,
    filePath = "Example/Path",
    fileType = FileType.Json,
    encryptionMethod = EncryptionMethod.AES,
    aesKey = aesKey,
    aesIV = aesIV,
    addToStorage = true
};

3. Create the Save File

After using the code below, you have successfully created an encrypted save file.

SaveFile saveFile = new SaveFile(saveFileSetupData);

Background Save File

To create a save file that will save and load data in the background, set the backgroundTask value to true.

SaveFileSetupData saveFileSetupData = new SaveFileSetupData()
{
    fileName = "Save File",
    saveLocation = SaveLocation.PersistentDataPath,
    filePath = "Example/Path",
    fileType = FileType.Json,
    encryptionMethod = EncryptionMethod.None,
    addToStorage = true,
    backgroundTask = true
};

SaveFile saveFile = new SaveFile(saveFileSetupData);

You can set this value at any time during runtime, and the save file will use a background or main thread accordingly.

saveFile.backgroundTask = false;

Last updated