【发布时间】:2019-09-27 22:23:09
【问题描述】:
我有一个游戏,我需要存储这些数据:
- 国家
- 城市
- 等级
有 5 个国家,每个国家 5 个城市,每个城市有 x 个级别。
存储这些数据的最佳方式是什么,我希望存储关卡详细信息,例如完成、花费的时间等
然后我希望通过 Leveldata[countryindex, cityindex] 访问级别数据。
我想到了多维列表或字典,但想知道你们认为最佳做法是什么?
我还需要以 JSON 格式保存这些数据。
谢谢
【问题讨论】:
我有一个游戏,我需要存储这些数据:
有 5 个国家,每个国家 5 个城市,每个城市有 x 个级别。
存储这些数据的最佳方式是什么,我希望存储关卡详细信息,例如完成、花费的时间等
然后我希望通过 Leveldata[countryindex, cityindex] 访问级别数据。
我想到了多维列表或字典,但想知道你们认为最佳做法是什么?
我还需要以 JSON 格式保存这些数据。
谢谢
【问题讨论】:
创建一个合适的数据模型,例如:
public class Level
{
public TimeSpan TimeTaken { get; set; }
// level specific data
}
public class City
{
public IList<Level> Levels { get; set; }
}
public class Country
{
public IList<City> Cities { get; set; }
}
然后您可以简单地使用JSON.NET 对 JSON 进行序列化/反序列化,例如:
string json = JsonConvert.SerializeObject(country);
【讨论】:
Kirill Polishchuk 提到的类结构,标记为可序列化,但带有一些数组运算符重载可以满足您的需要。
然后您可以使用 Unity 的内置 JsonUtility 序列化为 json 并写入磁盘(或 PlayerPrefs 作为字符串)。在下面的代码中,我向 LevelData 类添加了一个 Save 和 Load 方法来为您执行此操作。
[System.Serializable]
public class Level
{
public int Score;
// ...
}
[System.Serializable]
public class City
{
public List<Level> Levels = new List<Level>();
}
[System.Serializable]
public class Country
{
public List<City> Cities = new List<City>();
public City this[int cityIndex]
{
get
{
if (cityIndex < 0 || cityIndex >= Cities.Count)
{
return null;
}
else
{
return Cities[cityIndex];
}
}
}
}
[System.Serializable]
public class LevelData
{
public List<Country> Countries = new List<Country>();
public List<Level> this[int countryIndex, int cityIndex]
{
get
{
if (countryIndex < 0 || countryIndex >= Countries.Count)
{
return null;
}
else
{
City city = Countries[countryIndex][cityIndex];
if (city != null)
{
return city.Levels;
}
else
{
return null;
}
}
}
}
public void Save(string path)
{
string json = JsonUtility.ToJson(this);
// Note: add IO exception handling here!
System.IO.File.WriteAllText(path, json);
}
public static LevelData Load(string path)
{
// Note: add check that the path exists, and also a try/catch for parse errors
LevelData data = JsonUtility.FromJson<LevelData>(path);
if (data != null)
{
return data;
}
else
{
return new LevelData();
}
}
您可能需要添加设置器来创建国家和城市对象。或者,如果您将 LevelData 作为公共变量添加到脚本中,此结构将在 Unity 编辑器中可见。
以及添加和保存级别:
LevelData data = LevelData.Load(path);
// Here I assume your countries and cities already exist in the structure
List<Level> levels = data[1,2];
// todo: check that levels is not null!
Level l = new Level();
// add all info to l
levels.Add(l);
data.Save(path);
【讨论】:
[,] 运算符返回对List<Level> 的引用,您只需在此列表中调用Add 即可添加您的新关卡。我已经更新了答案以显示这一点。