Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    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

    kiryuha161

    Joined:
    Aug 27, 2022
    Posts:
    2
    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):
    1.  
    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.     }
    15.  
    Here is the code with the items, they are then added to the inventory.
    Code (CSharp):
    1.  
    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 };
    8.  
    9.     public GameObject Character;
    10.     public Sprite[] Sprites;
    11.     public ItemData ItemDataScript;
    12.  
    13.     [SerializeField] private List<ItemData> items = new List<ItemData>();
    14.  
    15.     private int _currentItem;
    16.     private int _currentDefence;
    17.  
    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;
    34.  
    35.         if (HasItems[index])
    36.         {
    37.             Quantity[index]++;
    38.         }
    39.      
    40.         SaveItems();//
    41.     }
    42.  
    Save
    Code (CSharp):
    1.  
    2. public void SaveItems()
    3.     {
    4.         //List<ItemData> dataList = new List<ItemData>();//
    5.  
    6.         for (int i = 0; i < HasItems.Length; i++)
    7.         {
    8.             if (HasItems[i])
    9.             {
    10.                
    11.                 string name = NameItems[i];
    12.              
    13.                 int quantity = Quantity[i];
    14.                 int defence = DefenceItems[i];
    15.                 ItemDataScript = new ItemData(name, quantity, defence);
    16.                
    17.                 items.Add(ItemDataScript);
    18.                
    19. string json = JsonUtility.ToJson(items);//
    20.        
    21.      
    22.         File.WriteAllText(Path.Combine(Application.persistentDataPath, "/items.json"), json);
    23.             }
    24.         }
    25.  
    Code (CSharp):
    1.  
    2. items.Clear();
    3.         string filePath = Path.Combine(Application.persistentDataPath, "/items.json");
    4.      
    5.  
    6.         if (File.Exists(filePath))
    7.         {
    8.            
    9.             string json = File.ReadAllText(filePath);
    10.          
    11.      
    12.             items = JsonUtility.FromJson<List<ItemData>>(json);
    13.  
    14.            
    15.             foreach (ItemData data in items)//
    16.             {
    17.                 int index = GetIndex(data.Name);
    18.  
    19.                 if (index != -1)
    20.                 {
    21.                     HasItems[index] = true;
    22.                     SetQuantity(data.Name, data.Quantity);
    23.                     Debug.Log("Ok");
    24.                 }
    25.  
    26.                 else
    27.                 {
    28.                     Debug.Log("fail");
    29.                 }
    30.             }
    31.         }
    32.     }
    33.  
    The check in the download method at foreach is not output to the console.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    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
    Debug.Log()
    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
    Debug.Log("Problem!",this);


    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: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    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:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

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

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

    -------------------------------------------------------

    Load/Save steps:

    https://forum.unity.com/threads/save-system-questions.930366/#post-6087384

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

    https://forum.unity.com/threads/save-system.1232301/#post-7872586

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

    https://forum.unity.com/threads/use...lds-in-editor-and-build.1327059/#post-8394573

    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
    new
    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:

    https://gist.github.com/kurtdekker/7db0500da01c3eb2a7ac8040198ce7f6

    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.

    https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide

    ---------------------------------------------------------------------

    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:

    https://forum.unity.com/threads/weapon-inventory-and-how-to-script-weapons.1046236/#post-6769558

    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:

    https://forum.unity.com/threads/opt...n-an-asteroid-belt-game.1395319/#post-8781697
     
    kiryuha161 likes this.
  3. kiryuha161

    kiryuha161

    Joined:
    Aug 27, 2022
    Posts:
    2
    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.