Unity魔方算法训练器JSON读取时触发NullReferenceException求助
问题原因分析
Resources.Load仅能加载Unity项目中Resources目录下已被导入为资源的文件,运行时通过File.WriteAllText创建的文件不会被Unity自动识别为资源,因此textFile返回null,访问textFile.text时触发NullReferenceException。- 你生成的基础JSON缺少
algorithms字段,反序列化后该列表会为null,后续操作也可能引发异常。
解决方案
1. 改用直接读取文件内容(推荐)
放弃Resources.Load,直接通过文件路径读取内容,适配运行时创建/修改的文件。修改UpdateCollections方法:
//algManager public void UpdateCollections() { algorithms.Clear(); info = new DirectoryInfo(path); var fileInfo = info.GetFiles("*.txt"); foreach (FileInfo file in fileInfo) { // 直接读取文件文本,跳过Resources加载逻辑 string jsonContent = File.ReadAllText(file.FullName); AlgorithmCollection collection = JsonConvert.DeserializeObject<AlgorithmCollection>(jsonContent); // 初始化空列表,避免后续空引用 if (collection.algorithms == null) { collection.algorithms = new List<AlgorithmBase>(); } algorithms.Add(collection); } }
2. 修正基础JSON生成逻辑
确保生成的JSON包含algorithms字段,避免反序列化后列表为null:
public string GetBaseFileCollection(string collectionName) { // 初始化带空列表的集合对象 var baseCollection = new AlgorithmCollection { collectionName = collectionName, algorithms = new List<AlgorithmBase>() }; // 用JsonConvert序列化,避免手动拼接JSON出错 return JsonConvert.SerializeObject(baseCollection, Formatting.Indented); }
3. 优化文件存储路径
建议使用Unity跨平台通用的PersistentDataPath作为存储路径,避免权限或路径识别问题:
// 初始化时设置路径 string path = Path.Combine(Application.persistentDataPath, "AlgorithmCollections"); // 确保目录存在 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }
额外注意事项
[SerializeField]仅在Unity编辑器序列化时生效,Json.NET反序列化不识别该属性,你的字段均为public,无需额外处理;若涉及私有字段,需添加[JsonProperty]属性。- 对于
Mover.Face枚举,Json.NET默认支持序列化/反序列化,若需以字符串形式存储,可添加[JsonConverter(typeof(StringEnumConverter))]属性。
内容的提问来源于stack exchange,提问作者BoringPlatypus
相关产品推荐
相关产品推荐

