ESave
ESave
ESave
  • ESave Documentation
  • Pro Comparison
  • đŸ•šī¸Getting Started
    • Installation
    • Example Scenes
    • Components
      • Save File Setup
      • Save Storage
  • đŸ“Ŋī¸Videos
    • Tutorial
  • 📄Scripting
    • Saving & Loading
      • Saving
      • Loading
      • Custom Serializable Objects
      • Example Script
    • Runtime Save Creation
      • Creating a Save File
      • Infinite Saves
        • Infinite Save Scripting
    • Runtime Save Deletion
    • Understanding Background Save & Load
    • Using the Save Storage
  • đŸ› ī¸Support
    • Getting Help
  • 📚Changelogs
    • Latest Releases
  • ⭐Rate Me?
Powered by GitBook
On this page
  1. Scripting
  2. Saving & Loading

Example Script

This script saves the player's transform values when the game is exited and loads the transform values on start.

When saving a transform with ESave, only the position, rotation, and scale properties are saved.

using UnityEngine;
using Esper.ESave;

public class SaveLoadExample : MonoBehaviour
{
    // Const data ID
    private const string playerTransformDataKey = "PlayerTransform";

    [SerializeField]
    private Transform playerTransform;

    private SaveFileSetup saveFileSetup;
    private SaveFile saveFile;

    private void Start()
    {
        // Get save file component attached to this object
        saveFileSetup = GetComponent<SaveFileSetup>();
        saveFile = saveFileSetup.GetSaveFile();

        // Load game
        LoadGame();
    }

    /// <summary>
    /// Loads the game.
    /// </summary>
    public void LoadGame()
    {
        // Check if the data exists in the file
        if (saveFile.HasData(playerPositionDataKey))
        {
            // Get Vector3 from a special method because Vector3 is not savable data
            var savableTransform = saveFile.GetTransform(playerPositionDataKey);
            playerTransform.CopyTransformValues(savableTransform);
        }

        Debug.Log("Loaded game.");
    }

    /// <summary>
    /// Saves the game.
    /// </summary>
    public void SaveGame()
    {
        saveFile.AddOrUpdateData(playerPositionDataKey, playerTransform);
        saveFile.Save();

        Debug.Log("Saved game.");
    }
    
    private void OnApplicationQuit()
    {
        SaveGame();
    }
}
PreviousCustom Serializable ObjectsNextRuntime Save Creation

Last updated 11 months ago

📄