Load

Summary: Load data by name, either synchronously or with a completion callback.

Description

Load data by name, either synchronously or with a completion callback. The synchronous overload waits for the read. The callback overload runs asynchronously and invokes the callback on Unity’s main thread.

Call either overload from Unity’s main thread. With the callback overload, storage that requires the main thread, such as PlayerPrefs, also reads there.

Declaration

C#
public static LoadResult<T> Load<T>(string name, SaveOptions options = null, Func<T> defaultValue = null);

public static void Load<T>(string name, Action<LoadResult<T>> callback, SaveOptions options = null, Func<T> defaultValue = null);

Parameters

ParameterTypeDescription
T—Type of the data to load.
namestringName of the save.
optionsSaveOptionsOptional. Selects the slot to read from. Null uses the default slot.
defaultValueFunc<T>Optional. Creates the fallback for Data when a load returns a failure status, including NotFound and Corrupt. The result keeps its failure status.
callbackAction<LoadResult<T>>Callback overload only. Called on the main thread with the result when the load is finished.

Returns

The synchronous overload returns LoadResult<T>. The callback overload passes that result to callback. Check IsSuccess to see whether Data contains loaded data. On failure, check Status even if Data contains a fallback.

Exceptions

ExceptionThrown when
ArgumentNullExceptionThe callback overload receives a null callback.
InvalidOperationExceptionThe method is called from a thread other than Unity’s main thread.

Example

Create either LoadPositionSynchronous.cs or LoadPositionWithCallback.cs using the matching block. Attach the script to an active GameObject. Run the synchronous example on the Save page once to create position-sync-example. Each script restores that position in Play mode.

Synchronous · C#
using Gley.SaveSystem;
using UnityEngine;

public class LoadPositionSynchronous : MonoBehaviour
{
    private void Start()
    {
        LoadResult<Vector3> result = API.Load<Vector3>("position-sync-example");

        if (result.IsSuccess)
        {
            transform.position = result.Data;
        }
        else
        {
            Debug.LogWarning($"Load failed ({result.Status}): {result.Message}", this);
        }
    }
}
With callback · C#
using Gley.SaveSystem;
using UnityEngine;

public class LoadPositionWithCallback : MonoBehaviour
{
    private void Start()
    {
        API.Load<Vector3>("position-sync-example", OnLoaded);
    }

    private void OnLoaded(LoadResult<Vector3> result)
    {
        if (result.IsSuccess)
        {
            transform.position = result.Data;
        }
        else
        {
            Debug.LogWarning($"Load failed ({result.Status}): {result.Message}", this);
        }
    }
}

Player progress in a file

Group the level, coins and checkpoint in one serializable PlayerProgress object. One API.Save call writes the whole object, and API.Load<PlayerProgress> restores it.

Use the File backend for your active platform. Check the Backend column under Tools › Gley › Save System › General. Default (File) also works.

The Save and Load pages share this example. Create PlayerProgressFileExample.cs once and attach it to a GameObject. Enter Play mode and choose Save Progress from the component’s Inspector menu. Change the values under Progress, then choose Load Progress to restore the saved values.

In a game, use the loaded progress when IsSuccess is true. Create a fresh profile only when Status is SaveStatus.NotFound. For other failures, report or handle the error before writing to that slot.

Player progress · C#
using System;
using Gley.SaveSystem;
using UnityEngine;

public class PlayerProgressFileExample : MonoBehaviour
{
    private const string SaveName = "player-progress-example";

    [SerializeField] private PlayerProgress _progress = new PlayerProgress();

    // Use these two Inspector commands to test saving and loading in Play mode.
    // In your game, call the Save System API from your own save and load code.
    [ContextMenu("Save Progress")]
    private void SaveProgress()
    {
        if (!Application.isPlaying)
        {
            return;
        }

        SaveResult result = API.Save(_progress, SaveName);
        Debug.Log($"Save result: {result.Status}", this);
    }

    [ContextMenu("Load Progress")]
    private void LoadProgress()
    {
        if (!Application.isPlaying)
        {
            return;
        }

        LoadResult<PlayerProgress> result = API.Load<PlayerProgress>(SaveName);
        if (!result.IsSuccess)
        {
            Debug.LogWarning($"Load failed ({result.Status}): {result.Message}", this);
            return;
        }

        _progress = result.Data;
        Debug.Log($"Loaded level {_progress.Level}, {_progress.Coins} coins, checkpoint {_progress.Checkpoint}.", this);
    }

    [Serializable]
    private sealed class PlayerProgress
    {
        [SerializeField] private string _checkpoint = "camp";
        [SerializeField] private int _level = 1;
        [SerializeField] private int _coins = 25;

        public string Checkpoint => _checkpoint;
        public int Level => _level;
        public int Coins => _coins;
    }
}

With the default folder settings, the file is Saves/default/player-progress-example.sav under Application.persistentDataPath. To find it in Unity, go to Tools › Gley › Save System › Save Viewer and choose Open save folder.

On This Page