【发布时间】:2019-03-04 19:01:20
【问题描述】:
我试图将一些项目存储为 JSON 文件并在运行时获取它们。我正在尝试创建 ItemDescription 对象的列表。但列表返回空。我没有收到任何错误,但是当我设置断点时,我看到listOfItems 在listOfItems = JsonUtility.FromJson<ItemList>(jsonString); 之后为空。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class ItemDictionary : MonoBehaviour
{
private Dictionary<ushort, ItemDescription> itemDictionary = new Dictionary<ushort, ItemDescription>();
private ItemList listOfItems;
private string path;
void Start()
{
path = Application.streamingAssetsPath + "/itemDescription.json";
if (File.Exists(path))
{
string jsonString = File.ReadAllText(path);
listOfItems = JsonUtility.FromJson<ItemList>(jsonString);
//Populate dictionary via JSON
foreach (ItemDescription item in listOfItems.itemList)
{
Debug.Log(item.itemName);
//itemDictionary.Add(item.id, item);
}
}
else
{
Debug.LogError("ITEMDESCRIPTION FILE CANNOT BE FOUNDD");
}
}
}
[System.Serializable]
public class ItemList
{
public List<ItemDescription> itemList;
}
[System.Serializable]
public class ItemDescription
{
public string itemName;
public ushort id;
public string description;
public ushort stack;
public uint cost;
}
JSON 文件
{
"Items": [
{
"itemName": "Regular Dirt",
"id": 1,
"description": "Dirty dirt",
"stack": 500,
"cost": 0
},
{
"itemName": "Regular Stone",
"id": 2,
"description": "It's hard",
"stack": 500,
"cost": 0
},
{
"itemName": "Regular Sand",
"id": 4,
"description": "It gets everywhere.",
"stack": 500,
"cost": 0
}
]
}
我已经尝试将所有类型转换为字符串,将ItemDescription 类重命名为Items,ItemList 类为Items。
【问题讨论】:
-
你的课程是用“Serializable”装饰的吗? (docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html)
-
@RyanWilson 雅。我将它们放在
ItemDictionary类的底部。他们都是Serializable。