This script works, but its quite tedious. As I have to manually code a for loop for each ItemData[] variables in the itemDB.
Question: Is there a simpler way to get all the variables in the ItemDB ScriptableObject?
public class InventoryManager : MonoBehaviour
{
public Dictionary<string, ItemData> itemDB = new Dictionary<string, ItemData>();
public ItemDB itemDBAsset;
// (NOTE: this is the annoying part as its not scalable)
private void ProcessItemDB()
{
for (int i = 0; i < itemDBAsset.consumables.Length; i++)
itemDB.Add(itemDBAsset.consumables[i].icon.name, itemDBAsset.consumables[i]);
for (int i = 0; i < itemDBAsset.weapons.Length; i++)
itemDB.Add(itemDBAsset.weapons[i].icon.name, itemDBAsset.weapons[i]);
for (int i = 0; i < itemDBAsset.armors.Length; i++)
itemDB.Add(itemDBAsset.armors[i].icon.name, itemDBAsset.armors[i]);
for (int i = 0; i < itemDBAsset.accessories.Length; i++)
itemDB.Add(itemDBAsset.accessories[i].icon.name, itemDBAsset.accessories[i]);
for (int i = 0; i < itemDBAsset.materials.Length; i++)
itemDB.Add(itemDBAsset.materials[i].icon.name, itemDBAsset.materials[i]);
for (int i = 0; i < itemDBAsset.materials.Length; i++)
itemDB.Add(itemDBAsset.craftingScrolls;[i].icon.name, itemDBAsset.craftingScrolls;[i]);
for (int i = 0; i < itemDBAsset.foods;.Length; i++)
itemDB.Add(itemDBAsset.foods[i].icon.name, itemDBAsset.foods[i]);
}
.
public class ItemDB : ScriptableObject
{
public ItemData[] consumables;
public ItemData[] weapons;
public ItemData[] armors;
public ItemData[] accessories;
public ItemData[] materials;
public ItemData[] craftingScrolls;
public ItemData[] foods;
}
[System.Serializable]
public class ItemData
{
public string name;
public Sprite icon;
public string description;
}
I once helped out a bit on something called
SerializableDictionary
which would be really helpful for your usecase.Back then I created a modified version and called it
EnumDictionary
. This one simply serializes a dictionary and makes sure that each value of the givenenum
exists exactly once. (You simply put it anywhere in your project)Then you can configure each of these items for that according enum value.
So what? -> well using that EnumDictionary I would change your code like this:
and then
Then as with a usual dictionary (in fact internally the
EnumDictionary
deserializes the stored values into a normalDictionary
) you can access each item by e.g. usingor iterate through all of them using
so you would do