我会先检查几件事:
- 检查文件是否确实存在。只需使用一个小的
Debug.Log(File.Exists(path))。
- 尝试其他路径 -> 保存类似:Application.persistentDataPath。在 Windows 上,这将为您提供如下内容:%userprofile%\AppData\Local\Packages\LocalState。这可确保您能够读取/写入文件。
- 用实际数据填写
List,以便区分保存的列表和默认列表。
编辑 1:
我刚刚复制了您的代码并对其进行了一些调整。它并不完美,但它肯定对我有用。
状态数据:
using System;
[Serializable]
public struct StateData
{
public string m_Name;
public string m_Location;
public string m_GameText;
public StateData(string name, string location, string gameText)
{
m_Name = name;
m_Location = location;
m_GameText = gameText;
}
}
StateDataCollection:
using System;
using System.Collections.Generic;
[Serializable]
public class StateDataCollection
{
public List<StateData> m_StateData;
public StateDataCollection() => m_StateData = new List<StateData>();
}
JSONReader:
using System.IO;
using UnityEngine;
public class JSONReader : MonoBehaviour
{
private const string FILENAME = "StateData.json";
private string m_path;
public string FilePath {
get => m_path;
set => m_path = value;
}
void Start()
{
FilePath = Path.Combine(Application.persistentDataPath, FILENAME);
Debug.Log(FilePath);// delete me
StateDataCollection stateDataCollection = new StateDataCollection();
stateDataCollection.m_StateData.Add(new StateData("Peter", "X", "123"));
stateDataCollection.m_StateData.Add(new StateData("Annie", "Y", "42"));
stateDataCollection.m_StateData.Add(new StateData("TheGuyFromTheSupermarket", "Supermarket", "666"));
SaveStateDataCollectionToPath(FilePath, stateDataCollection);
LoadStateDataCollectionFromPath(FilePath);
}
private void SaveStateDataCollectionToPath(string path, StateDataCollection stateDataCollection)
{
// ToDo: some checks on path and stateDataCollection
string json = JsonUtility.ToJson(stateDataCollection, true);// prettyPrint active
File.WriteAllText(path, json);
}
private void LoadStateDataCollectionFromPath(string path)
{
if(File.Exists(path)) {
Debug.Log($"File exists at: {path}");// delete me
string json = File.ReadAllText(path);
StateDataCollection stateDataCollection = JsonUtility.FromJson<StateDataCollection>(json);
// delete me
Debug.Log($"StateDataCollection count: { stateDataCollection.m_StateData.Count}");
int i = 1;
stateDataCollection.m_StateData.ForEach(o => {
Debug.Log(
$"Item Nr.: {i}\n" +
$"Name: {o.m_Name}\n" +
$"Location: {o.m_Location}\n" +
$"GameText: {o.m_GameText}\n\n");
++i;
});
}
}
}
我还添加了几个Debug.Log()s 用于测试。
用法:
在SaveStateDataCollectionToPath(FilePath, stateDataCollection); 活动的情况下运行一次,在没有它的情况下运行一次。 控制台应显示 3 个项目。
编辑 2:
我认为您的问题可能是违反命名约定。 File 需要using System.IO;,在File 旁边还包含Path。不幸的是,您还将const string 命名为“路径”。