Home >Backend Development >C++ >How to Robustly Save and Load Game Data in Unity3D using JSON and PlayerPrefs?
Unity3D high -efficiency game status preservation method
BinaryFormatter method may encounter problems in some cases (especially on iOS devices). It depends on class matching during deepertine, so it may cause data loss after updating or remodeling. In addition, it needs to add environment variables to iOS to prevent problems.
In order to solve these restrictions and provide more powerful solutions, it is recommended to use PlayerPrefs and JSON to save the game status. PlayerPrefs provides a convenient mechanism that can use a small amount of data as key values for storage, and JSON (JavaScript Object Notation) provides a structured format that can easily convert it to objects and convert it from objects.
This method can be further enhanced by converting the JSON string into byte array and using
and to read and write data. File.WriteAllBytes
File.ReadAllBytes
The following is a general -purpose demonstration of this technology.
DataSaver
<code class="language-csharp">public class DataSaver { // 保存数据 public static void SaveData<T>(T dataToSave, string dataFileName) { string path = Path.Combine(Application.persistentDataPath, dataFileName + ".json"); // 使用 Application.persistentDataPath 保证数据持久性 string jsonData = JsonUtility.ToJson(dataToSave, true); byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData); // 使用 UTF8 编码 Directory.CreateDirectory(Path.GetDirectoryName(path) ?? ""); // 创建目录,处理空路径 try { File.WriteAllBytes(path, jsonBytes); Debug.Log("数据已保存到: " + path); } catch (Exception e) { Debug.LogError("保存数据失败: " + path + "\n错误信息: " + e.Message); } } // 加载数据 public static T LoadData<T>(string dataFileName) { string path = Path.Combine(Application.persistentDataPath, dataFileName + ".json"); if (!File.Exists(path)) { Debug.Log("文件不存在: " + path); return default(T); } byte[] jsonBytes = null; try { jsonBytes = File.ReadAllBytes(path); Debug.Log("数据已加载自: " + path); } catch (Exception e) { Debug.LogError("加载数据失败: " + path + "\n错误信息: " + e.Message); return default(T); } string jsonData = Encoding.UTF8.GetString(jsonBytes); // 使用 UTF8 编码 return JsonUtility.FromJson<T>(jsonData); } }</code>
This example improves the error processing, uses a more common type
<code class="language-csharp">// 要保存的示例类 [Serializable] public class PlayerInfo { public List<int> IDs = new List<int>(); public List<int> Amounts = new List<int>(); public int Life = 0; public float HighScore = 0; } // 保存数据 PlayerInfo saveData = new PlayerInfo(); saveData.Life = 99; saveData.HighScore = 40; DataSaver.SaveData(saveData, "playerData"); // 加载数据 PlayerInfo loadedData = DataSaver.LoadData<PlayerInfo>("playerData"); if (loadedData != null) { Debug.Log("生命值: " + loadedData.Life); Debug.Log("最高分: " + loadedData.HighScore); }</code>, and uses
to ensure the durability of data and correct the coding problem. Remember to add T
attributes to your class. Application.persistentDataPath
The above is the detailed content of How to Robustly Save and Load Game Data in Unity3D using JSON and PlayerPrefs?. For more information, please follow other related articles on the PHP Chinese website!