Search Unity

Help !!! How to Save and Load Inventory items to the database?

Discussion in 'Scripting' started by SonEvil, Oct 23, 2017.

  1. SonEvil

    SonEvil

    Joined:
    Jul 29, 2015
    Posts:
    11
    thank you for reading! I was learned to make a Inventory system of gamegrind. now I'm looking to save my inventory , but still can not do it. Please help me !?

    Tutorial in here :


    This my Inventory script :
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class Inventory : MonoBehaviour {
    7.  
    8.     GameObject inventoryPanel;
    9.     public GameObject slotPanel;
    10.     ItemDatabase database;
    11.     public GameObject inventorySlot;
    12.     public GameObject inventoryItem;
    13.  
    14.     int slotAmount;
    15.     public List<Item> items = new List<Item>();
    16.     public List<GameObject> slots = new List<GameObject>();
    17.  
    18.     public GameObject toolTip;
    19.  
    20.  
    21.     void Start () {
    22.         database = GetComponent<ItemDatabase>();
    23.  
    24.         slotAmount = 20;
    25.         inventoryPanel = GameObject.Find("Inventory Panel");
    26.        
    27.         for (int i = 0; i < slotAmount; i++)
    28.         {
    29.             items.Add(new Item());
    30.             slots.Add(Instantiate(inventorySlot));
    31.             slots[i].GetComponent<Slot>().id = i;
    32.             slots[i].transform.SetParent(slotPanel.transform);
    33.         }
    34.     }
    35.  
    36.     void Update()
    37.     {
    38.         if (Input.GetKeyDown(KeyCode.U))
    39.         {
    40.             AddItem(5);
    41.             AddItem(6);
    42.             AddItem(7);
    43.         }
    44.  
    45.     }
    46.  
    47.     public void AddItem(int id)
    48.     {
    49.         Item itemToAdd = database.FetchItemByID(id);
    50.         if (itemToAdd.Stackable && CheckIfItemIsInInventory(itemToAdd))
    51.         {
    52.             for (int i = 0; i < items.Count; i++)
    53.             {
    54.                 if (items[i].ID == id)
    55.                 {
    56.                     ItemData data = slots[i].transform.GetChild(0).GetComponent<ItemData>();
    57.                     data.amount++;
    58.                     data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
    59.                     break;
    60.                 }
    61.             }
    62.         }
    63.         else
    64.         {
    65.             for (int i = 0; i < items.Count; i++)
    66.             {
    67.                 if (items[i].ID == -1)
    68.                 {
    69.                     items[i] = itemToAdd;
    70.                     GameObject itemObj = Instantiate(inventoryItem);
    71.                     itemObj.GetComponent<ItemData>().item = itemToAdd;
    72.                     itemObj.GetComponent<ItemData>().slot = i;
    73.                     itemObj.transform.SetParent(slots[i].transform);
    74.                     itemObj.transform.position = Vector2.zero;
    75.                     itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
    76.                     itemObj.name = itemToAdd.Title;
    77.                     ItemData data = slots[i].transform.GetChild(0).GetComponent<ItemData>();
    78.                     data.amount = 1;
    79.                     break;
    80.                 }
    81.             }
    82.         }
    83.     }
    84.  
    85.     public void RemoveItem(int id)
    86.     {
    87.         Item itemToRemove = database.FetchItemByID(id);
    88.         if (itemToRemove.Stackable && CheckIfItemIsInInventory(itemToRemove))
    89.         {
    90.             for (int j = 0; j < items.Count; j++)
    91.             {
    92.                 if (items[j].ID == id)
    93.                 {
    94.                     ItemData data = slots[j].transform.GetChild(0).GetComponent<ItemData>();
    95.                     data.amount--;
    96.                     data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
    97.                     if (data.amount == 0)
    98.                     {
    99.                         Destroy(slots[j].transform.GetChild(0).gameObject);
    100.                         items[j] = new Item();
    101.                         closealltab();
    102.                         break;
    103.                     }
    104.                     if (data.amount == 1)
    105.                     {
    106.                         slots[j].transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = "";
    107.                         break;
    108.                     }
    109.                     break;
    110.                 }
    111.             }
    112.         }
    113.         else
    114.         {
    115.             for (int i = 0; i < items.Count; i++)
    116.             {
    117.                 if (items[i].ID != -1 && items[i].ID == id)
    118.                 {
    119.                     Destroy(slots[i].transform.GetChild(0).gameObject);
    120.                     items[i] = new Item();
    121.                     break;
    122.                 }
    123.             }
    124.         }
    125.     }
    126.  
    127.     bool CheckIfItemIsInInventory(Item item) {
    128.         for (int i = 0; i < items.Count; i++)
    129.         {
    130.             if (items[i].ID == item.ID)
    131.                 return true;
    132.         }
    133.         return false;
    134.     }
    135. }
    136.  
    And this is ItemDatabase script :

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using LitJson;
    5. using System.IO;
    6.  
    7. public class ItemDatabase : MonoBehaviour
    8. {
    9.     private List<Item> database = new List<Item>();
    10.     private JsonData itemData;
    11.  
    12.     void Start()
    13.     {
    14.         itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Items.json"));
    15.         ConstructItemDatabase();
    16.  
    17.         //Debug.Log(FetchItemByID(0).Description);
    18.     }
    19.  
    20.     public Item FetchItemByID(int id) {
    21.         for (int i = 0; i < database.Count; i++)
    22.             if (database [i].ID == id)
    23.                 return database [i];
    24.         return null;
    25.     }
    26.  
    27.     void ConstructItemDatabase()
    28.     {
    29.         for (int i = 0; i < itemData.Count; i++)
    30.         {
    31.             database.Add(new Item((int)itemData[i]["id"], itemData[i]["title"].ToString(), (int)itemData[i]["value"],
    32.                 (int)itemData[i]["stats"]["defence"], (int)itemData[i]["stats"]["energy"], itemData[i]["description"].ToString(),
    33.                 (bool)itemData[i]["stackable"], (int)itemData[i]["rarity"], itemData[i]["slug"].ToString()));
    34.         }
    35.     }
    36. }
    37.  
    38. public class Item
    39. {
    40.     public int ID { get; set; }
    41.     public string Title { get; set; }
    42.     public int Value { get; set; }
    43.     public int Defence { get; set; }
    44.     public int Energy { get; set; }
    45.     public string Description { get; set; }
    46.     public bool Stackable { get; set; }
    47.     public int Rarity { get; set; }
    48.     public string Slug { get; set; }
    49.     public Sprite Sprite { get; set; }
    50.  
    51.     public Item(int id, string title, int value, int defence, int energy, string description, bool stackable, int rarity, string slug)
    52.     {
    53.         this.ID = id;
    54.         this.Title = title;
    55.         this.Value = value;
    56.         this.Energy = energy;
    57.         this.Defence = defence;
    58.         this.Description = description;
    59.         this.Stackable = stackable;
    60.         this.Rarity = rarity;
    61.         this.Slug = slug;
    62.         this.Sprite = Resources.Load<Sprite>("Sprites/Items/" + slug);
    63.  
    64.     }
    65.  
    66.     public Item()
    67.     {
    68.         this.ID = -1;
    69.     }
    70. }
    71.  
    ItemData script :

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.EventSystems;
    5. using System;
    6.  
    7. public class ItemData : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerEnterHandler,IPointerExitHandler {
    8.  
    9.     public Item item;
    10.     public int amount;
    11.     public int slot;
    12.  
    13.     private Inventory inv;
    14.     private UseItem useItem;
    15.     private Tooltip tooltip;
    16.     private Vector2 offset;
    17.  
    18.  
    19.     void Start()
    20.     {
    21.         inv = GameObject.Find("Inventory").GetComponent<Inventory>();
    22.         useItem = GameObject.Find("Inventory").GetComponent<UseItem>();
    23.         tooltip = inv.GetComponent<Tooltip>();
    24.         this.transform.SetParent(inv.slots[slot].transform);
    25.         this.transform.position = inv.slots[slot].transform.position;
    26.     }
    27.  
    28.     public void OnBeginDrag(PointerEventData eventData)
    29.     {
    30.         if (item != null) {
    31.             offset = eventData.position - new Vector2(this.transform.position.x, this.transform.position.y);
    32.             this.transform.SetParent(this.transform.parent.parent);
    33.             this.transform.position = eventData.position - offset;
    34.             GetComponent<CanvasGroup>().blocksRaycasts = false;
    35.         }
    36.     }
    37.  
    38.     public void OnDrag(PointerEventData eventData)
    39.     {
    40.         if (item != null) {
    41.             this.transform.position = eventData.position - offset;
    42.         }
    43.     }
    44.  
    45.     public void OnEndDrag(PointerEventData eventData)
    46.     {
    47.         this.transform.SetParent (inv.slots[slot].transform);
    48.         this.transform.position = inv.slots [slot].transform.position;
    49.         GetComponent<CanvasGroup>().blocksRaycasts = true;
    50.     }
    51.  
    52.     public void OnPointerExit(PointerEventData eventData)
    53.     {
    54.         tooltip.Deactivate();
    55.     }
    56.  
    57.     public void OnPointerEnter(PointerEventData eventData)
    58.     {
    59.         tooltip.Activate(item);
    60.     }
    61. }
    62.  
    Thank !!! ^^
     
  2. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    Are you receiving an error? What is the issue that you are having.
     
  3. SonEvil

    SonEvil

    Joined:
    Jul 29, 2015
    Posts:
    11
    hello ! my problem problems are save inventory.
    I tried writing a paragraph to save but it does not work @@

    Code (CSharp):
    1. void OnGUI()
    2.     {
    3.         if (GUI.Button(new Rect(40, 400, 100, 40), "Save"))
    4.             SaveInventory();
    5.         if (GUI.Button(new Rect(40, 450, 100, 40), "Load"))
    6.             LoadInventory();      
    7.     }
    8.  
    9.     void SaveInventory()
    10.     {
    11.         for (int i = 0; i < items.Count; i++)
    12.             PlayerPrefs.SetInt("Items " + i, items[i].ID);
    13.         Debug.Log("Inventory saved");
    14.     }
    15.  
    16.     void LoadInventory()
    17.     {      
    18.         for (int i = 0; i < items.Count; i++)          
    19.             items[i] = PlayerPrefs.GetInt("Items " + i,-1) >= 0 ? items[PlayerPrefs.GetInt("Items " +i)]: new Item();      
    20.         Debug.Log("Inventory loaded");
    21.     }
     
  4. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    What part does not work? Do you see the Debug.Log statements? And what do you mean "writing a paragraph"?
     
  5. SonEvil

    SonEvil

    Joined:
    Jul 29, 2015
    Posts:
    11
    items values not saved, code on no work, I mount it in inventory script. Yes! i see the Debug.Log statements. My goal is to find a way to save the inventory above :)
     
  6. laxbrookes

    laxbrookes

    Joined:
    Jan 9, 2015
    Posts:
    235
    If you are modifying PlayerPrefs... you need to call
    Code (csharp):
    1. PlayerPrefs.Save()