你将如何存储这些数据

How would you store this data

我有一个游戏,我需要存储这些数据:

有 5 个国家,每个国家 5 个城市,每个城市 x 个级别。

存储此数据的最佳方式是什么,我希望存储关卡详细信息,例如已完成、花费的时间等

然后我希望通过 Leveldata[countryindex, cityindex] 访问关卡数据。

我想到了多维列表或字典,但想知道你们认为什么是最佳实践?

我还需要将此数据保存在 JSON 中。

谢谢

创建一个合适的 data-model,例如:

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到serialize/deserializeto/fromJSON,例如:

string json = JsonConvert.SerializeObject(country);

Kirill Polishchuk 提到的 classes 结构,标记为 Serializable,但一些数组运算符重载将满足您的需要。

然后您可以使用 Unity 的 built-in JsonUtility 序列化为 json 并写入磁盘(或 PlayerPrefs 作为字符串)。在下面的代码中,我向 LevelData class 添加了一个 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();
        }
    }

您可能需要添加 setter 来创建国家和城市对象。或者,如果您将 LevelData 作为 public 变量添加到脚本,此结构将在 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);