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();
}
}