C# 从json文件填充列表
我试图根据我的json文件填充3个列表 目标是从json文件加载数据,分配给我的列表,以便我可以添加/修改值,然后将它们重新保存到json文件中 然而,这条线似乎有问题C# 从json文件填充列表,c#,unity3d,C#,Unity3d,我试图根据我的json文件填充3个列表 目标是从json文件加载数据,分配给我的列表,以便我可以添加/修改值,然后将它们重新保存到json文件中 然而,这条线似乎有问题 level.Add(new Level(i, (string)levelsJson[i]["name"]), props ); 特别是道具 我将非常感谢如何填充我的级别列表和修改解决方案 这是我的json结构 [ { "id": 0, "name": "Greatest level", "props
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;
}
}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
使用System.IO;
使用LitJson;
公共类json:MonoBehavior{
私有列表级别=新列表();
私有JsonData LEVESSON;
无效开始(){
负荷水平();
}
void LoadLevels(){
levelsJson=JsonMapper.ToObject(File.ReadAllText(Application.dataPath+“/StreamingAssets/Levels.json”);
//这就是我试图填充列表的地方
对于(int i=0;i
我看到的一个问题是,您正在初始化初始for循环中的级别列表以填充级别列表。这将导致在每次迭代开始时将Level
变量重新初始化为新的空列表
尝试移动行:List level=new List();
行前:
for(int i=0;i
放入json文件,它将显示json结构的样子。现在,看看如何在Unity中读取json的答案。