我正在尝试使用 json 文件创建库存系统。基本上,我有我的 json 文件:
[
{
"name":"Potion",
"id":1,
"balance":5
},
{
"name":"Neutral Bomb",
"id":2,
"balance": 4
}
]
我有我的 c# 文件:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using LitJson;
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
public int Balance { get; set; }
public Item(string name1, int id1, int balance1) {
Name = name1;
Id = id1;
Balance = balance1;
}
}
public class InventoryAttempt : MonoBehaviour
{
public static void BalanceChange(string filePath, int ID, int change)
{
string jsonString = File.ReadAllText(Application.dataPath + filePath);
List<Item> itemList = JsonMapper.ToObject<List<Item>>(jsonString);
itemList [ID].Balance += change;
jsonString = JsonMapper.ToJson (itemList).ToString();
File.WriteAllText (Application.dataPath + filePath, jsonString);
}
void Start()
{
BalanceChange ("/Scripts/inventory.json", 1, 1);
}
}
在我的 c# 文件中,我想访问一个项目,比如说中性炸弹项目。怎么进去编辑中性炸弹的平衡?我想使用项目 ID 来告诉要编辑哪个对象。我想创建一个列表,其中每个元素都是存储在 Json 文件中的项目之一,但我不确定如何将它们分开。我应该怎么办?
MissingMethodException: Method not found: 'Default constructor not found...ctor() of Item'.
System.Activator.CreateInstance (System.Type type, Boolean nonPublic) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:368)
System.Activator.CreateInstance (System.Type type) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:254)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ReadValue (System.Type inst_type, LitJson.JsonReader reader)
LitJson.JsonMapper.ToObject[List`1] (System.String json)
InventoryAttempt.BalanceChange (System.String filePath, Int32 ID, Int32 change) (at Assets/Scripts/InventoryAttempt.cs:26)
InventoryAttempt.Start () (at Assets/Scripts/InventoryAttempt.cs:34)