INDEX 中的 C# 交互更改所有 INDEX 值 JSON

C# Interaction in INDEX change all INDEX values JSON

我正在用 C# 做一个 INVENTORY 系统。我有一个大小为 6 的数组,它包含 JSONDATA 对象。但是我有一个问题,当我尝试更改一个特定索引中的一个对象字段时,所有包含对象的索引也更改了该字段。例子:

Debug.Log ("SLOT 0 = "+inventory[0]["count"]);//Output 4
Debug.Log ("SLOT 1 = "+inventory[1]["count"]);//Output 4
inventory [0] ["count"] = 5; //Change INDEX 0 field "count" to 5
Debug.Log ("SLOT 0 = "+inventory[0]["count"]);//Output 5 --CHECK
Debug.Log ("SLOT 1 = "+inventory[1]["count"]);//Output 5 --WRONG

我不知道为什么会这样,有人可以帮助我吗? 对不起我的英语,我来自巴西。 谢谢

--编辑 你好@Steve,谢谢你的回答。我进行了编辑,因为我无法评论你对所有代码的回答。 我使用 for 运行 数组的所有索引,如果我有一个空索引,我将一个 JSONDATA 对象(ItemToAdd)添加到索引中。 ItemToAdd 是一个 JSONDATA 对象: { "id": 1, "name": "Item 1", "type": "Tool", "description": "1", "count": 0, "sellable": false, "sellprice": 0, "buyable": false, "buyprice": 0, "stackable": true, "maxcount": 10, "slug": "Item_1" }

运行所有数组的代码。

`for (int i = 0; i < container.Length; i++)
    {
        if (container [i] == null)
        {
            container [i] = ItemToAdd;//ADD ITEM TO ARRAY
            if (newItemCount > newItemMaxCount)
            {
                container [i] ["count"] = newItemMaxCount;
                newItemCount -= newItemMaxCount;
                newContainer = container;
            }
            else 
            {
                container [i] ["count"] = newItemCount;
                newItemCount = 0;
                left = newItemCount;
                itemSettings.NewItemCount = left;
                newContainer = container;
                return true;
            }
        }
    }`

Variable有什么需要解释的,尽管说。 再次感谢您的帮助,对不起我的英语。

您可以尝试编写一个简单的方法来反序列化您的 JSONDATA 实例并重建一个新的 JSONDATA 实例

JSONDATA MakeCopy(JSONDATA source)
{
     string result = JsonConvert.SerializeObject(source);
     return JsonConvert.DeserializeObject<JSONDATA>(result);
}

现在可以将此对象添加到数组中的第

container[i] = MakeCopy(ItemToAdd);