I am creating inventory system for my game and problem is that i need to create system to store multiple values to my device.
I know there are PlayerPrefs
but with that i can only store 2 values (let's say key for one and value for second), but i need something like table. So i have to store something like this in single line:
inventorySlot
itemID
amount
this is simple 3 size value, but also i would need to store 4, 5, or more.
So how can i achieve this?
Here is current code where problem is that storing to json is not working. Look at comment at the end of Debug.Log to see what it displays.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InventoryModel
{
public List<InventoryItem> InventoryItems;
public InventoryModel()
{
InventoryItems = new List<InventoryItem>();
}
}
public class InventoryItem
{
public int inventorySlot;
public int itemID;
public float amount;
}
public class Inventory : MonoBehaviour
{
private int inventorySlots = 5;
public Text itemSlot1;
void Start ()
{
AddItemToInventory(1, 0, 2000);
LoadInventory();
}
void Update ()
{
}
public static void AddItemToInventory(int slot, int itemID, float amount)
{
InventoryModel im = new InventoryModel();
InventoryItem ii = new InventoryItem();
ii.inventorySlot = slot;
ii.itemID = itemID;
ii.amount = amount;
im.InventoryItems.Add(ii);
foreach(InventoryItem ia in im.InventoryItems)
{
Debug.Log(ia.itemID + "-" + ia.amount + "-" + ia.inventorySlot); //Display 0-2000-1
}
string jsonString = JsonUtility.ToJson(im);
Debug.Log(jsonString); //Display {}
PlayerPrefs.SetString("PlayerInventory", jsonString);
}
private void LoadInventory()
{
foreach(InventoryItem ii in LoadInventoryFromPref().InventoryItems)
{
//Doesnt enter this loop
Debug.Log(ii.inventorySlot);
Debug.Log(ii.itemID);
Debug.Log(ii.amount);
Debug.Log("====");
}
}
private static InventoryModel LoadInventoryFromPref()
{
string test = PlayerPrefs.GetString("PlayerInventory");
Debug.Log(test); //display {}
return JsonUtility.FromJson<InventoryModel>(test);
}
private static int GetMaxInventorySlots()
{
if(PlayerPrefs.HasKey("MIS"))
{
return PlayerPrefs.GetInt("MIS");
}
else
{
return 0;
}
}
}