how to save and load inventory in unity using json

35 Views Asked by At

I am making a game in Unity and I want to save and load inventory using JSON. but I do not know how to save the data and load it either. as I use mono behavior in the Spwan script. this has 4 different scripts. when i try it will save the bool only but not the inside the inventory. and i use the i button to set active the inventory canvas

I tried my best to get but I couldn't, I want to make inventory save and load

1. Inventory script
public class InventoryData : MonoBehaviour
{
    public bool[] isFull;
    public string[] slotNames;
}
2.Slot script
public class Slots : MonoBehaviour
{
    private Inventory inventory;
    public int i;

    private void Start()
    {
        inventory = GameObject.FindGameObjectWithTag("Inventory").GetComponent<Inventory>();
    }

    private void Update()
    {
        if (transform.childCount <= 0)
        {
            inventory.isFull[i] = false;
        }
    }

    public void Dropitem()
    {
        foreach(Transform child in transform)
        {
            GameObject.Destroy(child.gameObject);
        }
    }
}

3. this is script where i add or sub the item to inventory.

public class NPCSlot : MonoBehaviour
{
    public Image itemImage;
    public Text itemName;
    public Text itemPrice;
    public Text itemSellPrice;
    public Text itemExportPrice;

    public GameObject itemToBuy;
    //public GameObject Sloot;

    public Inventory inventory;
    public Character player;
    public CoinScript coinScript;
    public Slots slots;

    // Start is called before the first frame update
    void Start()
    {
        itemName.text = itemToBuy.GetComponent<Spwan>().itemName;
        itemPrice.text = /*"Price : " +*/ itemToBuy.GetComponent<Spwan>().itemPrice.ToString();
        itemSellPrice.text =itemToBuy.GetComponent<Spwan>().sellPrice.ToString();
        itemImage.sprite = itemToBuy.GetComponent<Image>().sprite;
        itemExportPrice.text = itemToBuy.GetComponent<Spwan>().exportPrice.ToString();
        inventory = GameObject.FindGameObjectWithTag("Inventory").GetComponent<Inventory>();

    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void Buy()
    {
        for (int i = 0; i < inventory.slots.Length; i++)
        {
            if (inventory.isFull[i] == false && coinScript.money >= 0 && itemToBuy.GetComponent<Spwan>().itemPrice <= coinScript.money)
            {
                // ITEM CAN BE ADDED TO INVENTORY !
                inventory.isFull[i] = true;
                Instantiate(itemToBuy, inventory.slots[i].transform, false);
                coinScript.money -= itemToBuy.GetComponent<Spwan>().itemPrice;
                break;
            }
        }
    }

    public void BuyOption(int Hunger)
    {
        coinScript.money -= itemToBuy.GetComponent<Spwan>().itemPrice;
        player.Hunger += Hunger;
    }

    public void BuyFromShop()
    {
        for (int i = 0; i < inventory.slots.Length; i++)
        {
            if (inventory.isFull[i] == false && coinScript.money >= 0 && itemToBuy.GetComponent<Spwan>().sellPrice <= coinScript.money)
            {
                // ITEM CAN BE ADDED TO INVENTORY !
                inventory.isFull[i] = true;
                Instantiate(itemToBuy, inventory.slots[i].transform, false);
                coinScript.money -= itemToBuy.GetComponent<Spwan>().sellPrice;
                break;
            }
        }
    }
 public void Sell(string itemName) // itemName is itemName in Spwan Script
    {
        // Iterate through each slot in the inventory
        for (int i = 0; i < inventory.slots.Length; i++)
        {
            // Check if the current slot is occupied
            if (inventory.isFull[i])
            {
                // Get the item in the slot
                GameObject item = inventory.slots[i].transform.GetChild(0).gameObject;

                // Get the item's script component
                Spwan itemSpawn = item.GetComponent<Spwan>();

                // Check if the item's name matches the item to sell
                if (itemSpawn.itemName == itemName)
                {
                    // Sell the item and update player's money
                    coinScript.money += itemSpawn.sellPrice;

                    // Destroy the sold item from the inventory slot
                    Destroy(item);

                    // Set the slot as empty
                    inventory.isFull[i] = false;

                    // Exit the loop after selling the item
                    break;
                }
            }
        }
    }


    public void Export(string itemName) // itemName is itemName in Spwan Script
    {
        // Iterate through each slot in the inventory
        for (int i = 0; i < inventory.slots.Length; i++)
        {
            // Check if the current slot is occupied
            if (inventory.isFull[i])
            {
                // Get the item in the slot
                GameObject item = inventory.slots[i].transform.GetChild(0).gameObject;

                // Get the item's script component
                Spwan itemSpawn = item.GetComponent<Spwan>();
                
                // Check if the item's name matches the item to sell
                if (itemSpawn.itemName == itemName)
                {
                    // Sell the item and update player's money
                    coinScript.money += itemSpawn.exportPrice;

                    // Destroy the sold item from the inventory slot
                    Destroy(item);

                    // Set the slot as empty
                    inventory.isFull[i] = false;

                    // Exit the loop after selling the item
                    break;
                }
            }
        }
    }
}

4. Spawn script which is attached to all item which goes to inventory

public class Spwan : MonoBehaviour
{
    public GameObject itemPrefab;
    public string itemName;
    public int itemPrice;
    public int sellPrice;
    public int exportPrice;
}

and i use idatapersistence for saving.

5. this is gamedata script where i save the data


[System.Serializable]
public class GameData
{
    public long lastUpdated;
    public int moneyCount;
    public float hungerMax;
    public int currentMonthData;
    public int currentDayData;
    public float currentTimeData;
    public Vector3 playerPosition;
    public bool isApartmentActiveData;
    public SerializableDictionary<string, bool> coinsCollected;
    public AttributesData playerAttributesData;

    // the values defined in this constructor will be the default values
    // the game starts with when there's no data to load
    public GameData() 
    {
        this.moneyCount = 500;
        this.hungerMax = 100f;
        playerPosition = new Vector3(3.75f,-3.75f,0f);
        currentMonthData = 1;
        currentDayData = 1;
        currentTimeData = 6f; // 6:00 AM
        isApartmentActiveData = false;

    }

    public int GetPercentageComplete() 
    {
        // figure out how many coins we've collected
        int totalCollected = 0;
        foreach (bool collected in coinsCollected.Values) 
        {
            if (collected) 
            {
                totalCollected++;
            }
        }

        // ensure we don't divide by 0 when calculating the percentage
        int percentageCompleted = -1;
        if (coinsCollected.Count != 0) 
        {
            percentageCompleted = (totalCollected * 100 / coinsCollected.Count);
        }
        return percentageCompleted;
    }
}
0

There are 0 best solutions below