-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInventoryConverterHelper.cs
104 lines (90 loc) · 3.06 KB
/
InventoryConverterHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System.Collections.Generic;
using Unity.Plastic.Newtonsoft.Json.Linq;
using Unity.Plastic.Newtonsoft.Json;
using UnityEngine;
public static class InventoryConverterHelper
{
public enum ConversionType
{
JSON
}
static ScriptableObjectLocator scriptableObjectLocator = null;
public static void ImportInventory(string json, InventoryChannel inventoryChannel, ConversionType conversionType = ConversionType.JSON, bool additive = false)
{
if (json != null)
{
if (!additive) // Clear inventory if not being added
{
inventoryChannel.OnInventoryClear();
}
switch (conversionType) // Switch between conversion types
{
case ConversionType.JSON:
ImportInventoryFromJSON(json, inventoryChannel);
break;
}
}
}
private static void ImportInventoryFromJSON(string json, InventoryChannel inventoryChannel)
{
JArray obj = JArray.Parse(json);
foreach (var item in obj)
{
uint uid = (uint)item["Uid"]; // Get item Uid
InventorySystem.InventoryItem inventoryItem = FindItem(uid); // Find corresponding item
uint quantity = (uint)item["Quantity"]; // Get quantity of item
inventoryChannel.RaiseLootItem(inventoryItem, quantity); // Add it to inventory
}
}
public static string ExportInventory(InventoryHolder inventoryChannel, ConversionType conversionType = ConversionType.JSON)
{
switch (conversionType)
{
case ConversionType.JSON:
return ExportInventoryToJSON(inventoryChannel);
}
return "";
}
private static string ExportInventoryToJSON(InventoryHolder inventoryHolder)
{
string jsonData = "";
List<ItemSlot> inventory = new List<ItemSlot>();
inventoryHolder.Inventory.ForEach
((slot) =>
{
if (slot.Item != null)
{
inventory.Add(new ItemSlot(slot.Item.Uid, slot.Quantity));
}
});
jsonData = JsonConvert.SerializeObject(inventory);
return jsonData;
}
struct ItemSlot
{
public ItemSlot(uint Uid, uint Quantity)
{
this.Uid = Uid;
this.Quantity = Quantity;
}
public uint Uid { get; }
public uint Quantity { get; }
}
public static InventorySystem.InventoryItem FindItem(uint uid)
{
if (scriptableObjectLocator == null) // Set if not set yet
{
scriptableObjectLocator = Resources.Load<ScriptableObjectLocator>("ScriptableObjects/SOLocator");
}
scriptableObjectLocator.ScriptableObjects.TryGetValue(uid, out ScriptableObject scriptableObject);
if (scriptableObject != null)
{
InventorySystem.InventoryItem item = scriptableObject as InventorySystem.InventoryItem;
if (item != null)
{
return item;
}
}
return null;
}
}