Skip to main content

Class SaveData

Cross-platform persistent key-value store that serialises SaveDataFormat subclasses to GZip-compressed JSON files on disk.

[DisallowMultipleComponent]
public sealed class SaveData : MonoBehaviour, IUnityGameService

Inheritance​

Implements​

IUnityGameService

Remarks​

The compression step is intentional: simulation sessions generate large data files (ScriptableVariable values, survey responses, activity logs) and GZip typically halves the on-disk size of JSON. The tradeoff is CPU time at read/write, which is hidden by the async API.

A two-level in-memory cache is maintained alongside the disk files:

  • temporarily — deserialised SaveDataFormat objects ready for use.
  • jsonTemporarily — raw JSON strings preloaded by Action) but not yet deserialised. Deserialisation is deferred until first access to keep startup fast.

When a key is requested, the cache is checked first; only a cache miss triggers disk I/O.

On WebGL, Unity's IndexedDB-backed file system requires an explicit SyncFile JavaScript interop call after every write to flush changes from the in-memory FS to persistent storage. The _syncFile() helper wraps this call so the rest of the code stays platform-agnostic.

Data can be preloaded by executing Action), the performance of Get methods will improve. Data can be saved by executing:

Data can be retrieved by executing:

Data can be deleted by executing:

If you want to save and retrieve your own data, implement a class that inherits from SaveDataFormat.

Below is a reference URL (Information will appear if you search for "unity ios android internal storage" in web search etc.)

Properties​

SaveDirectoryPath​

Path to actually save data

public string SaveDirectoryPath { get; }

Property Value​

string

Methods​

Delete(string[])​

Delete the file key (file name (without extension)) saved in the terminal.

public void Delete(string[] keys)

Parameters​

NameTypeDescription
keysstring[]Keys (file name (no extension))

Delete(string[], Action)​

Delete the file key (file name (without extension)) saved in the terminal.

public void Delete(string[] keys, Action deleteResponseCallback)

Parameters​

NameTypeDescription
keysstring[]Keys (file name (no extension))
deleteResponseCallbackActionresponse callback

DeleteContainsKey(string)​

Deletes all saved files whose names contain the specified substring.

public void DeleteContainsKey(string containsKey)

Parameters​

NameTypeDescription
containsKeystringThe substring to match against saved file names.

ExistsSaveData(string)​

Is the data of the specified key (data name) saved?

public bool ExistsSaveData(string key)

Parameters​

NameTypeDescription
keystringSpecified key (data name)

Returns​

bool — true:Existing false:does not exist

GetCustomData<T>(string, bool)​

Retrieves custom data of a type derived from SaveDataFormat.

public T GetCustomData<T>(string key, bool isStoreTemporarilyWhenLoad = false) where T : SaveDataFormat, new()

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
isStoreTemporarilyWhenLoadboolIf true, the retrieved data will be cached in memory after loading, improving subsequent access speed at the cost of increased memory usage.

Returns​

T — The retrieved custom data instance, or a new instance if loading fails.

Type Parameters​

NameTypeDescription
TThe type of the custom data.

GetCustomDataInBackground<T>(string, Action<T>, bool)​

Initiates an asynchronous operation to retrieves custom data of a type derived from SaveDataFormat.

public void GetCustomDataInBackground<T>(string key, Action<T> getResponseCallback, bool isStoreTemporarilyWhenLoad = false) where T : SaveDataFormat

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
getResponseCallbackAction<T>Callback invoked with the retrieved value.
isStoreTemporarilyWhenLoadboolIf true, the retrieved data will be cached in memory after loading, improving subsequent access speed at the cost of increased memory usage.

Type Parameters​

NameTypeDescription
TThe type of the custom data.

GetDataNamesByContainsKey(string[], bool)​

Retrieves a list of data file names that contain any of the specified substrings.

public string[] GetDataNamesByContainsKey(string[] keys, bool clearExtension = false)

Parameters​

NameTypeDescription
keysstring[]The substrings to look for in the file names.
clearExtensionboolIf true, the returned file names will exclude their extensions; otherwise, extensions are included.

Returns​

string[] — An array of file names that contain any of the specified keys.

Examples​

string[] keys = { "session", "log" };
var names = GetDataNamesByContainsKey(keys);

GetDataNamesByStartsWithKey(string[], bool)​

Retrieves a list of data file names that start with any of the specified prefixes.

public string[] GetDataNamesByStartsWithKey(string[] keys, bool clearExtension = false)

Parameters​

NameTypeDescription
keysstring[]The prefixes to match at the start of each file name.
clearExtensionboolIf true, the returned file names will exclude their extensions; otherwise, extensions are included.

Returns​

string[] — An array of file names that start with any of the specified keys.

Examples​

string[] keys = { "config", "user" };
var names = GetDataNamesByStartsWithKey(keys);

GetFloat(string, bool)​

Retrieves Single data.

public float GetFloat(string key, bool isStoreTemporarilyWhenLoad = false)

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
isStoreTemporarilyWhenLoadboolIf true, the retrieved data will be cached in memory after loading, improving subsequent access speed at the cost of increased memory usage.

Returns​

float — The retrieved float value.

GetFloatInBackground(string, Action<float>, bool)​

Initiates an asynchronous operation to retrieves Single data.

public void GetFloatInBackground(string key, Action<float> getResponseCallback, bool isStoreTemporarilyWhenLoad = false)

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
getResponseCallbackAction<float>Callback invoked with the retrieved value.
isStoreTemporarilyWhenLoadboolIf true, the retrieved data will be cached in memory after loading, improving subsequent access speed at the cost of increased memory usage.

GetInt(string, bool)​

Retrieves Int32 data.

public int GetInt(string key, bool isStoreTemporarilyWhenLoad = false)

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
isStoreTemporarilyWhenLoadboolIf true, the retrieved data will be cached in memory after loading, improving subsequent access speed at the cost of increased memory usage.

Returns​

int — The retrieved integer value.

GetIntInBackground(string, Action<int>, bool)​

Initiates an asynchronous operation to retrieves Int32 data.

public void GetIntInBackground(string key, Action<int> getResponseCallback, bool isStoreTemporarilyWhenLoad = false)

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
getResponseCallbackAction<int>Callback invoked with the retrieved value.
isStoreTemporarilyWhenLoadboolIf true, the retrieved data will be cached in memory after loading, improving subsequent access speed at the cost of increased memory usage.

GetMatchingDataNames(Func<string, bool>, bool)​

Returns the names of saved files that satisfy predicate, sorted by the leading numeric portion of each filename.

public string[] GetMatchingDataNames(Func<string, bool> predicate, bool clearExtension = false)

Parameters​

NameTypeDescription
predicateFunc<string, bool>
clearExtensionbool

Returns​

string[]

Examples​

The following example demonstrates how to retrieve file names that contain specific keys:

string[] keys = { "user", "log" };
string[] result = GetMatchingDataNames(name => keys.Any(key => name.Contains(key)));

Remarks​

Files are sorted by extracting the leading digits from each filename (e.g., session_42.dat → 42) so that numerically named records are returned in log order rather than lexicographic order. Files with no digits in their name sort last (sort key is int.MaxValue).

GetSaveDataPath(string)​

Get the path to save the specified key (data name)

public string GetSaveDataPath(string key)

Parameters​

NameTypeDescription
keystringkey (data name)

Returns​

string — Path to save the key (data name)

GetString(string, bool)​

Retrieves String data.

public string GetString(string key, bool isStoreTemporarilyWhenLoad = false)

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
isStoreTemporarilyWhenLoadboolIf true, the data will also be retained in memory cache after loading.

Returns​

string — The retrieved string value.

GetStringInBackground(string, Action<string>, bool)​

Initiates an asynchronous operation to retrieves String data.

public void GetStringInBackground(string key, Action<string> getResponseCallback, bool isStoreTemporarilyWhenLoad = false)

Parameters​

NameTypeDescription
keystringThe key under which the data is stored.
getResponseCallbackAction<string>Callback invoked with the retrieved value.
isStoreTemporarilyWhenLoadboolIf true, the retrieved data will be cached in memory after loading, improving subsequent access speed at the cost of increased memory usage.

LoadAllInBackground(Action)​

Initiates an asynchronous operation to get all the data from the terminal's local directory.

public void LoadAllInBackground(Action loadedCallback)

Parameters​

NameTypeDescription
loadedCallbackActionGet response callback

RemoveJsonTemporarily(string)​

Deletes specified data from temporarily stored data (jsonTemporarily)

(��Please note that this does not operate on saved data)

public void RemoveJsonTemporarily(string key)

Parameters​

NameTypeDescription
keystringKey (data name) to be deleted

RemoveTemporarily(string)​

Deletes specified data from temporarily held data (temporarily)

(��Please note that this does not operate on saved data)

public void RemoveTemporarily(string key)

Parameters​

NameTypeDescription
keystringKey (data name) to be deleted

SaveCustomData<T>(string, T, bool)​

Synchronously save data in a unique format that inherits from SaveDataFormat.

public bool SaveCustomData<T>(string key, T data, bool isStoreTemporarilyWhenSave = false) where T : SaveDataFormat

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
dataTThe data to be saved.
isStoreTemporarilyWhenSaveboolIf true, the data will be retained in memory cache after saving.

Returns​

bool

Type Parameters​

NameTypeDescription
T

SaveCustomDataInBackground<T>(string, T, Action<bool>, bool)​

Initiates an asynchronous operation to save data in a unique format that inherits from SaveDataFormat.

public void SaveCustomDataInBackground<T>(string key, T data, Action<bool> saveResponseCallback, bool isStoreTemporarilyWhenSave = false) where T : SaveDataFormat

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
dataTThe data to be saved.
saveResponseCallbackAction<bool>Callback invoked with the result of the save operation.
isStoreTemporarilyWhenSaveboolIf true, the data will be retained in memory cache after saving.

Type Parameters​

NameTypeDescription
T

SaveFloat(string, float, bool)​

Synchronously saves an Single value.

public bool SaveFloat(string key, float data, bool isStoreTemporarilyWhenSave = false)

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
datafloatThe data to be saved.
isStoreTemporarilyWhenSaveboolIf true, the data will also be retained in memory cache.

Returns​

bool — true if the save operation was successful; otherwise, false.

SaveFloatInBackground(string, float, Action<bool>, bool)​

Initiates an asynchronous operation to save the specified Single data in the background.

public void SaveFloatInBackground(string key, float data, Action<bool> saveResponseCallback, bool isStoreTemporarilyWhenSave = false)

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
datafloatThe data to be saved.
saveResponseCallbackAction<bool>Callback invoked with the result of the save operation.
isStoreTemporarilyWhenSaveboolIf true, the data will be retained in memory cache after saving.

SaveInt(string, int, bool)​

Synchronously saves an Int32 value.

public bool SaveInt(string key, int data, bool isStoreTemporarilyWhenSave = false)

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
dataintThe data to be saved.
isStoreTemporarilyWhenSaveboolIf true, the data will also be retained in memory cache.

Returns​

bool — true if the save operation was successful; otherwise, false.

SaveIntInBackground(string, int, Action<bool>, bool)​

Initiates an asynchronous operation to save the specified Int32 data in the background.

public void SaveIntInBackground(string key, int data, Action<bool> saveResponseCallback, bool isStoreTemporarilyWhenSave = false)

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
dataintThe integer data to be saved.
saveResponseCallbackAction<bool>A callback invoked with the result of the save operation.
isStoreTemporarilyWhenSaveboolIf true, the data will be retained in memory cache after saving.

SaveString(string, string, bool)​

Synchronously saves an String value.

public bool SaveString(string key, string data, bool isStoreTemporarilyWhenSave = false)

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
datastringThe data to be saved.
isStoreTemporarilyWhenSaveboolIf true, the data will also be retained in memory cache.

Returns​

bool — true if the save operation was successful; otherwise, false.

SaveStringInBackground(string, string, Action<bool>, bool)​

Initiates an asynchronous operation to save the specified String data in the background.

public void SaveStringInBackground(string key, string data, Action<bool> saveResponseCallback, bool isStoreTemporarilyWhenSave = false)

Parameters​

NameTypeDescription
keystringThe key under which the data will be saved.
datastringThe data to be saved.
saveResponseCallbackAction<bool>Callback invoked with the result of the save operation.
isStoreTemporarilyWhenSaveboolIf true, the data will be retained in memory cache after saving.

StoreJsonTemporarily(string, string)​

Temporarily retain the specified Json data (*Please note that it is not saved at this point)

public void StoreJsonTemporarily(string key, string json)

Parameters​

NameTypeDescription
keystringSpecified key (data name)
jsonstringJson data to save

StoreTemporarily(string, SaveDataFormat)​

Temporarily retain the specified data (*Please note that it is not saved at this point)

public void StoreTemporarily(string key, SaveDataFormat data)

Parameters​

NameTypeDescription
keystringSpecified key (data name)
dataSaveDataFormatData to save

TryGetInstance(out SaveData)​

Attempts to retrieve the SaveData singleton instance. Returns false if the instance doesn't exist.

public static bool TryGetInstance(out SaveData instance)

Parameters​

NameTypeDescription
instanceSaveDataThe output SaveData instance.

Returns​

bool — True if the SaveData instance exists; otherwise, false.

  • Remarks
  • Properties
    • SaveDirectoryPath
  • Methods
    • Delete(string[])
    • Delete(string[], Action)
    • DeleteContainsKey(string)
    • ExistsSaveData(string)
    • GetCustomData<T>(string, bool)
    • GetCustomDataInBackground<T>(string, Action<T>, bool)
    • GetDataNamesByContainsKey(string[], bool)
    • GetDataNamesByStartsWithKey(string[], bool)
    • GetFloat(string, bool)
    • GetFloatInBackground(string, Action<float>, bool)
    • GetInt(string, bool)
    • GetIntInBackground(string, Action<int>, bool)
    • GetMatchingDataNames(Func<string, bool>, bool)
    • GetSaveDataPath(string)
    • GetString(string, bool)
    • GetStringInBackground(string, Action<string>, bool)
    • LoadAllInBackground(Action)
    • RemoveJsonTemporarily(string)
    • RemoveTemporarily(string)
    • SaveCustomData<T>(string, T, bool)
    • SaveCustomDataInBackground<T>(string, T, Action<bool>, bool)
    • SaveFloat(string, float, bool)
    • SaveFloatInBackground(string, float, Action<bool>, bool)
    • SaveInt(string, int, bool)
    • SaveIntInBackground(string, int, Action<bool>, bool)
    • SaveString(string, string, bool)
    • SaveStringInBackground(string, string, Action<bool>, bool)
    • StoreJsonTemporarily(string, string)
    • StoreTemporarily(string, SaveDataFormat)
    • TryGetInstance(out SaveData)