【发布时间】:2021-10-25 19:31:06
【问题描述】:
我有一个这样的 JSON 文件设置
{
"cards": [
{
"id": "sand_bags",
"type": "Structure",
"name": "Sand Bags",
"values": [
{
"civilian": 1,
"fiend": -1
}
],
"effectTexts": [
{
"civilian": "Add +1 to your BUNKER.",
"fiend": "Send any CIVILIAN'S +1 STRUCTURE to the SCRAPYARD."
}
],
"flavorTexts": [
{
"civilian": "They're just heavy bags with sand. Not much else to say, but they'll slow down an attack from a fiend. Good luck, you'll need it!",
"fiend": "You've spotted a pretty bad STRUCTURE in this BUNKER. Time to do some damage."
}
],
"staysOnField": [
{
"civilian": true,
"fiend": false
}
],
"amountInDeck": 5
}
]
}
我也有一个卡片脚本
[Serializable]
public class Cards
{
public Card[] cards;
}
[Serializable]
public class Card
{
public string id;
public string type;
public string name;
public int amountInDeck;
}
public class Values
{
public int civilian;
public int fiend;
}
然后我有一个 CardEffects 脚本用于我的功能。
public class CardEffects : MonoBehaviour
{
public TextAsset jsonFile;
public Values values;
void Start()
{
Cards cardsInJson = JsonUtility.FromJson<Cards>(jsonFile.text);
foreach (Card card in cardsInJson.cards)
{
Debug.Log("Card name: " + card.name + " with " + values.civilian + " in the deck.");
}
}
}
我已经搜索了所有内容,试图找出如何获取“值”对象的数组。我做到了这一点,无论 JSON 中“值”中的信息如何,打印的值始终为 0。如果我使类可序列化,我可以更改值并且它可以工作,但我希望这些值是它们在 JSON 中声明的任何值。有没有更好的方法来做到这一点?
请记住,我是 C# 和 Unity 的新手。我通常用 JS 编写代码,其中使用 JSON 文件对我来说没什么大不了的,我认为这是最好的方法。
【问题讨论】:
-
我认为您的班级
Card中根本没有字段Card...所以添加例如public Values[] values;,你应该没问题......一般来说,在 Unity 上下文中,你可能还想稍后添加项目,我总是更喜欢列表而不是数组;)