[System.Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
public float playerHealth;
public PlayerData(string name, int level, float health)
{
playerName = name;
playerLevel = level;
playerHealth = health;
}
}
PlayerData playerData = new PlayerData("Yapi", 10, 100f);
string json = JsonUtility.ToJson(playerData);
我們將使用推薦的 Simple Encryption 插件來進行 AES 加密。
確保你已在 Unity 中安裝了該插件。
File.WriteAllText
保存加密後的數據為了確保數據在下次啓動遊戲時可以被讀取
我們將加密後的 JSON 文本保存到 Unity 的 PersistentDataPath
中。
string filePath = System.IO.Path.Combine(Application.persistentDataPath, "playerData.dat");
System.IO.File.WriteAllText(filePath, encryptedData);
讀取保存的數據時,
我們需要先讀取文件內容,
再通過 AES 解密,將 JSON 轉換回原始的 Class。
public string DecryptData(string encryptedData, string encryptionKey)
{
return Encryption.DecryptString(encryptedData, encryptionKey);
}
string loadedData = System.IO.File.ReadAllText(filePath);
string decryptedData = DecryptData(loadedData, encryptionKey);
PlayerData loadedPlayerData = JsonUtility.FromJson<PlayerData>(decryptedData);
以下是完整的代碼示例,展示了從保存到讀取的整個流程:
using UnityEngine;
using SimpleEncryption;
public class DataManager : MonoBehaviour
{
private string encryptionKey = "your-encryption-key";
[ContextMenu("Save Data")]
public void SaveData()
{
PlayerData playerData = new PlayerData("Yapi", 10, 100f);
string json = JsonUtility.ToJson(playerData);
string encryptedData = Encryption.EncryptString(json, encryptionKey);
string filePath = System.IO.Path.Combine(Application.persistentDataPath, "playerData.dat");
System.IO.File.WriteAllText(filePath, encryptedData);
Debug.Log("Data Saved: " + encryptedData);
}
[ContextMenu("Load Data")]
public void LoadData()
{
string filePath = System.IO.Path.Combine(Application.persistentDataPath, "playerData.dat");
if (System.IO.File.Exists(filePath))
{
string loadedData = System.IO.File.ReadAllText(filePath);
string decryptedData = Encryption.DecryptString(loadedData, encryptionKey);
PlayerData loadedPlayerData = JsonUtility.FromJson<PlayerData>(decryptedData);
Debug.Log("Data Loaded: " + decryptedData);
}
else
{
Debug.LogWarning("Save file not found!");
}
}
}