Ejemplo básico y reutilizable de guardado JSON.
[System.Serializable]
public class SaveData
{
public int version = 1;
public int monedas;
public int nivel;
public float posX;
public float posY;
public float posZ;
}
using System.IO;
using UnityEngine;
public class SaveSystem : MonoBehaviour
{
private string ruta;
void Awake()
{
ruta = Path.Combine(
Application.persistentDataPath,
"save.json"
);
}
public void Guardar(
int monedas,
int nivel,
Vector3 posicion)
{
SaveData datos =
new SaveData();
datos.monedas = monedas;
datos.nivel = nivel;
datos.posX = posicion.x;
datos.posY = posicion.y;
datos.posZ = posicion.z;
string json =
JsonUtility.ToJson(
datos,
true
);
File.WriteAllText(
ruta,
json
);
}
public bool Cargar(
out SaveData datos)
{
datos = null;
if (!File.Exists(ruta))
{
return false;
}
try
{
string json =
File.ReadAllText(ruta);
datos =
JsonUtility
.FromJson<SaveData>(
json
);
return datos != null;
}
catch (System.Exception error)
{
Debug.LogError(
"No se pudo cargar: " +
error.Message
);
return false;
}
}
public void Borrar()
{
if (File.Exists(ruta))
{
File.Delete(ruta);
}
}
}
if (saveSystem.Cargar(
out SaveData datos))
{
monedas = datos.monedas;
nivel = datos.nivel;
transform.position =
new Vector3(
datos.posX,
datos.posY,
datos.posZ
);
}