【问题标题】:Unity json api problemsunity json api 问题
【发布时间】:2017-04-18 12:28:37
【问题描述】:

我目前正在尝试将 n x m 字段数组保存为文本文件中的 json。 我知道统一不支持顶级 JSON 反序列化的数组类型。因此我做了一个看起来像这样的类

public class Field{
    public int[][] id;
    public GameObject[][] gameObjectReference;
}

GameObject 数组是否存储在 json 文件中无关紧要,但我仍然想保存 id 数组。到目前为止,我有这个代码片段来测试它。

String[] aRows = System.IO.File.ReadAllLines(pathToSomeFile);       
field = new Field ();

    field.id = new int[aRows [0].Split(';').Length][];


    for (int i = 0; i < aRows [0].Split(';').Length; i++) {
        field.id [i] = new int[aRows.Length];
    }

    for (int y = 0; y < aRows.Length; y++) {
        for (int x = 0; x < aRows[y].Split(';').Length; x++) {
            field.id [x] [y] = int.Parse(aRows[y].Split(';')[x]);
        }   
    }

    GameManager.log (JsonUtility.ToJson (field));

但控制台只是说:

{}

我当前使用的文件看起来像这样

5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5

我的方法有什么问题?请帮忙!我就是想不通。

【问题讨论】:

    标签: c# arrays json unity3d unity5


    【解决方案1】:

    来自documentation

    在内部,此方法使用 Unity 序列化器;因此 您传入的对象必须由序列化程序支持:它必须是 MonoBehaviour、ScriptableObject 或普通类/结构,带有 应用了可序列化的属性。您想要的字段类型 必须被序列化器支持;不支持的字段 将被忽略,私有字段、静态字段和字段也将被忽略 应用了 NonSerialized 属性。

    它说提供的对象(在您的情况下是 Field 对象)必须是 MonoBehaviour、ScriptableObject 或普通类(您的情况) 应用了 Serializable 属性。您需要使用该属性。

    所以将属性添加到Field:

    [Serializable]
    public class Field{
        public int[][] id;
        public GameObject[][] gameObjectReference;
    }
    

    int[][] 是可序列化的,应该可以让你的代码工作,但是我不认为 GameObject[][] 是,我不太确定我们现在如何解决这个问题,所以它应该被忽略。不管怎样,先用标签试试你的代码,让我知道它是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 2015-03-02
      • 2012-08-21
      相关资源
      最近更新 更多