Lưu và tải dữ liệu bằng JSON (Newtonsoft)
C# Code
using UnityEngine;
using Newtonsoft.Json;
using System.IO;
public class GameData
{
public string playerName;
public int score;
public float health;
}
public class JsonSavingExample : MonoBehaviour
{
private string savePath;
void Awake()
{
savePath = Path.Combine(Application.persistentDataPath, "gamedata.json");
}
public void SaveGame()
{
GameData data = new GameData
{
playerName = "PlayerOne",
score = 1000,
health = 95.5f
};
string json = JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(savePath, json);
Debug.Log("Game data saved to: " + savePath);
}
public void LoadGame()
{
if (File.Exists(savePath))
{
string json = File.ReadAllText(savePath);
GameData data = JsonConvert.DeserializeObject<GameData>(json);
Debug.Log("Game data loaded:");
Debug.Log("Player Name: " + data.playerName);
Debug.Log("Score: " + data.score);
Debug.Log("Health: " + data.health);
}
else
{
Debug.LogWarning("Save file not found at: " + savePath);
}
}
}Sử dụng thư viện Newtonsoft.Json (Json.NET) để serialize và deserialize đối tượng C# thành chuỗi JSON, sau đó lưu vào tệp. Đây là một cách mạnh mẽ và linh hoạt để quản lý dữ liệu phức tạp. Yêu cầu đã cài đặt gói 'com.unity.newtonsoft-json'.