Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to make the items in the inventory preserved from session to session?

Discussion in 'Editor & General Support' started by kiryuha161, May 30, 2023.

  1. kiryuha161


    Aug 27, 2022
    Hello! I'm trying to make sure that inventory data, or rather items in it, are saved from session to session. It doesn't work. What am I doing wrong? I noticed that my json and filePath files are not being written. When debugging, it outputs {} to the console

    Here is a class with data
    Code (CSharp):
    2.  [System.Serializable]
    3.     public class ItemData
    4.     {
    5.         public string Name;
    6.         public int Quantity;
    7.         public int Defence;
    8.         public ItemData(string name, int quantity, int defence)
    9.         {
    10.             this.Name = name;
    11.             this.Quantity = quantity;
    12.             this.Defence = defence;
    13.         }
    14.     }
    Here is the code with the items, they are then added to the inventory.
    Code (CSharp):
    2. public class Items : MonoBehaviour
    3. {
    4.     public int[] DefenceItems = new int[] { 5, 10, 15, 20, 25 };
    5.     public bool[] HasItems = new bool[] { false, false, false, false, false };
    6.     public string[] NameItems = new string[] { "Bandit Pants", "Bulletproof cloak", "Bulletproof cloak Elbow", "Bulletproof cloak wrist", "Military Helmet" };
    7.     public int[] Quantity = new int[] { 0, 0, 0, 0, 0 };
    9.     public GameObject Character;
    10.     public Sprite[] Sprites;
    11.     public ItemData ItemDataScript;
    13.     [SerializeField] private List<ItemData> items = new List<ItemData>();
    15.     private int _currentItem;
    16.     private int _currentDefence;
    18.     private void Start()
    19.     {
    20.         LoadItems();
    21.     }
    22.     public void Equip(int index)
    23.     {
    24.         if (HasItems[index])
    25.         {
    26.             _currentItem = index;
    27.             _currentDefence = DefenceItems[_currentItem];
    28.             Character.GetComponent<SpriteRenderer>().sprite = Sprites[_currentItem];
    29.         }
    30.     }
    31.     public void AddItem(int index)
    32.     {
    33.         HasItems[index] = true;
    35.         if (HasItems[index])
    36.         {
    37.             Quantity[index]++;
    38.         }
    40.         SaveItems();//
    41.     }
    Code (CSharp):
    2. public void SaveItems()
    3.     {
    4.         //List<ItemData> dataList = new List<ItemData>();//
    6.         for (int i = 0; i < HasItems.Length; i++)
    7.         {
    8.             if (HasItems[i])
    9.             {
    11.                 string name = NameItems[i];
    13.                 int quantity = Quantity[i];
    14.                 int defence = DefenceItems[i];
    15.                 ItemDataScript = new ItemData(name, quantity, defence);
    17.                 items.Add(ItemDataScript);
    19. string json = JsonUtility.ToJson(items);//
    22.         File.WriteAllText(Path.Combine(Application.persistentDataPath, "/items.json"), json);
    23.             }
    24.         }
    Code (CSharp):
    2. items.Clear();
    3.         string filePath = Path.Combine(Application.persistentDataPath, "/items.json");
    6.         if (File.Exists(filePath))
    7.         {
    9.             string json = File.ReadAllText(filePath);
    12.             items = JsonUtility.FromJson<List<ItemData>>(json);
    15.             foreach (ItemData data in items)//
    16.             {
    17.                 int index = GetIndex(data.Name);
    19.                 if (index != -1)
    20.                 {
    21.                     HasItems[index] = true;
    22.                     SetQuantity(data.Name, data.Quantity);
    23.                     Debug.Log("Ok");
    24.                 }
    26.                 else
    27.                 {
    28.                     Debug.Log("fail");
    29.                 }
    30.             }
    31.         }
    32.     }
    The check in the download method at foreach is not output to the console.
  2. Kurt-Dekker


    Mar 16, 2013
    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as

    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: or this answer for Android:

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    function is an alias for Debug.Log() provided by the MonoBehaviour class.


    Load/Save steps:

    An excellent discussion of loading/saving in Unity3D by Xarbrough:

    Loading/Saving ScriptableObjects by a proxy identifier such as name:

    When loading, you can never re-create a MonoBehaviour or ScriptableObject instance directly from JSON. The reason is they are hybrid C# and native engine objects, and when the JSON package calls
    to make one, it cannot make the native engine portion of the object.

    Instead you must first create the MonoBehaviour using AddComponent<T>() on a GameObject instance, or use ScriptableObject.CreateInstance<T>() to make your SO, then use the appropriate JSON "populate object" call to fill in its public fields.

    If you want to use PlayerPrefs to save your game, it's always better to use a JSON-based wrapper such as this one I forked from a fellow named Brett M Johnson on github:

    Do not use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.


    A few more notes about inventories:

    These things (inventory, shop systems, character customization, dialog tree systems, crafting, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.

    Inventory code never lives "all by itself." All inventory code is EXTREMELY tightly bound to prefabs and/or assets used to display and present and control the inventory. Problems and solutions must consider both code and assets as well as scene / prefab setup and connectivity.

    Inventories / shop systems / character selectors all contain elements of:

    - a database of items that you may possibly possess / equip
    - a database of the items that you actually possess / equip currently
    - perhaps another database of your "storage" area at home base?
    - persistence of this information to storage between game runs
    - presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
    - interaction with items in the inventory or on the character or in the home base storage area
    - interaction with the world to get items in and out
    - dependence on asset definition (images, etc.) for presentation

    Just the design choices of such a system can have a lot of complicating confounding issues, such as:

    - can you have multiple items? Is there a limit?
    - if there is an item limit, what is it? Total count? Weight? Size? Something else?
    - are those items shown individually or do they stack?
    - are coins / gems stacked but other stuff isn't stacked?
    - do items have detailed data shown (durability, rarity, damage, etc.)?
    - can users combine items to make new items? How? Limits? Results? Messages of success/failure?
    - can users substantially modify items with other things like spells, gems, sockets, etc.?
    - does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
    - etc.

    Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.

    Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.

    Breaking down a large problem such as inventory:

    If you want to see most of the steps involved, make a "micro inventory" in your game, something whereby the player can have (or not have) a single item, and display that item in the UI, and let the user select that item and do things with it (take, drop, use, wear, eat, sell, buy, etc.).

    Everything you learn doing that "micro inventory" of one item will apply when you have any larger more complex inventory, and it will give you a feel for what you are dealing with.

    Breaking down large problems in general:
    kiryuha161 likes this.
  3. kiryuha161


    Aug 27, 2022
    I have already solved my problem, I just saw your message.
    JSON didn't accept my List. I had to make a separate class.
    Thank you very much for the detailed answer, I will definitely use this information and the links that you provided.