我正在尝试根据我的json文件填充3个列表。
目标是从json文件加载数据,分配给我的列表,以便我可以添加/修改值,然后将它们重新保存到json文件。
然而,此行似乎存在问题
level.Add(new Level(i, (string)levelsJson[i]["name"]), props );
特别是道具。
我非常感谢如何填充我的关卡列表并进行修改!
这是我的json结构
[
{
"id": 0,
"name": "Greatest level",
"props": [
{
"name": "stone",
"position": [ 4, 2 ]
},
{
"name": "tree",
"position": [ 1, 7 ]
}
]
},
{
"id": 1,
"name": "shitty level",
"props": [
{
"name": "stone",
"position": [ 2, -5 ]
},
{
"name": "tree",
"position": [ 15, 2 ]
}
]
}
]
这是我的整个代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using LitJson;
public class json : MonoBehaviour {
private List<Levels> levels = new List<Levels>();
private JsonData levelsJson;
void Start () {
LoadLevels();
}
void LoadLevels() {
levelsJson = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Levels.json"));
//This is where im trying to populate the lists
for(int i = 0; i < levelsJson.Count; i++) {
List<Level> level = new List<Level>();
List<Prop> props = new List<Prop>();
for(int prop = 0; prop < levelsJson[i]["props"].Count; prop++) {
props.Add(new Prop((string)levelsJson[i]["props"]["name"], new int[] { (int)levelsJson[i]["props"]["position"][0], (int)levelsJson[i]["props"]["position"][1]}));
}
level.Add(new Level(i, (string)levelsJson[i]["name"]), props );
}
}
public class Levels {
public Level[] levels;
public Levels(Level[] l) {
levels = l;
}
}
public class Level {
public int id;
public string name;
public Prop[] props;
public Level(int i, string n, Prop[] p) {
id = i;
name = n;
props = p;
}
}
public class Prop {
public string name;
public int[] position;
public Prop(string n, int[] p) {
name = n;
position = p;
}
}
答案 0 :(得分:0)
我看到的一个问题是你在初始for循环中初始化你的Level列表以填充你的Level列表。这将导致您的level
变量在每次迭代开始时重新初始化为新的空列表。
尝试移动该行:List<Level> level = new List<Level>();
行之前:
for(int i = 0; i < levelsJson.Count; i++) {