Unity中Save/Load系统失效:目录未创建且无法正常读写数据
Unity DataManager 加载失败问题修复
问题出在哪?
你的Load方法里犯了一个低级错误:用Directory.Exists()去检查文件路径是否存在。Directory.Exists()只认目录,不认带后缀的文件,所以哪怕文件真的存在,这个判断也永远返回false,每次加载都走默认值分支。
怎么修?
把文件存在性判断换成File.Exists(),同时可以额外加个目录检查,避免极端情况(比如保存后目录被手动删除)。
修复后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public static class DataManager { public static void Save<T>(T data, string path, string name) { path = Application.persistentDataPath + "/SaveData" + path; if (!Directory.Exists(path)) { Debug.Log("Create New Directory"); Directory.CreateDirectory(path); } path = path + "/" + name + ".txt"; Debug.Log("Save : " + path); string json = JsonUtility.ToJson(data, true); File.WriteAllText(path, json); } public static T Load<T>(string path, string name) where T : Savable, new() { // 拆分文件路径和目录路径,分别检查 string fullFilePath = Application.persistentDataPath + "/SaveData" + path + "/" + name + ".txt"; string directoryPath = Path.GetDirectoryName(fullFilePath); Debug.Log("Load : " + fullFilePath); T data = new T(); // 先确认目录存在,再检查文件是否存在 if (Directory.Exists(directoryPath) && File.Exists(fullFilePath)) { Debug.Log("Data Exist (Load)"); string json = File.ReadAllText(fullFilePath); data = JsonUtility.FromJson<T>(json); } else { Debug.Log("Data Don't Exist (Load)"); data.Name = name; } return data; } }
额外要注意的点
- 你的
Savable类里的字段,要么设为public,要么加[SerializeField]标签,不然JsonUtility没法把数据序列化/反序列化出来,就算加载成功也拿不到正确值。 - 如果
Savable是继承自MonoBehaviour的脚本类,JsonUtility没法正常工作,得改成普通的C#类。
内容的提问来源于stack exchange,提问作者Singul4r
相关产品推荐
相关产品推荐

