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 List.Remove(object) - unexpected behavior when used in [Serializable] class

Discussion in 'Scripting' started by AndrewAtCandlelight, Apr 25, 2023.

  1. AndrewAtCandlelight

    AndrewAtCandlelight

    Joined:
    May 3, 2022
    Posts:
    7
    Hello all!

    quick and abbreviated version of the problem:

    Code (CSharp):
    1.  
    2. [Serializable]
    3. public class SavedGameData
    4. {
    5.     public List<SavedItem> inventory;
    6. }
    7.  
    8. [System.Serializable]
    9. public struct SavedItem
    10. {
    11.     public string itemName;
    12.     public string id;
    13.     public Item.Quality quality;
    14.     public Item.Type type;
    15.     public int level;
    16.     public int count;
    17. }
    18.  
    Calling Remove(SavedItem item) on the inventory List returns true, and deletes the relevant data, however it does not change the length of the list - in the inspector "Element 4" or (whatever the appropriate index would be) shows up as an empty SavedItem in place of the removed struct. I would expect the element to be removed and the list to be updated to be 1 item shorter.

    Seems I am either missing something about how serializable lists interact with the inspector, missing something about expected behavior of List.Remove() (RemoveAt has the same issue), or the editor is not behaving correctly (2021.3.21f1)

    Any ideas? Thanks in advance!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,749
    Interesting. This sorta goes along with Unity not supporting serialization of null types.

    I'm not sure what the correct approach is here. Perhaps make a new list with the reduced count of items and assign it?? I suspect that wouldn't change the actual problem space.

    If you're using the Unity serialization system for saving that will only work in the editor, as you are likely already aware.

    Otherwise...

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

    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

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

    AND... more generally about inventories:

    These things (inventory, shop systems, character customization, 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
     
  3. AndrewAtCandlelight

    AndrewAtCandlelight

    Joined:
    May 3, 2022
    Posts:
    7
    Lots of good info in there, thanks!

    ^ this was exactly the next thing I tried

    Code (CSharp):
    1.         List<SavedItem> updatedList = new List<SavedItem>();
    2.         for (int i = 0; i < inventory.Count; i++)
    3.         {
    4.             if (inventory[i].id != item.id)
    5.             {
    6.                 updatedList.Add(item);
    7.             }
    8.         }
    9.         inventory = updatedList;
    More or less the same thing happens still - the list remains an incorrect size, with an empty struct at the end.

    I might just try to reimplement with basic arrays at this point. Would really like to understand what is happening here though.

    Say more about this? The following seems to work across mobile devices (note, GetPath() is tricky for Android)
    Code (CSharp):
    1.     public void LocalSave()
    2.     {
    3.         savedGameData.lastSaveTime_ticks = DateTime.Now.Ticks;
    4.         BinaryFormatter bf = new BinaryFormatter();
    5.         FileStream file = File.Create(GetPath() + "/SavedGame.dat");
    6.         bf.Serialize(file, savedGameData);
    7.         file.Close();
    8.     }
     
  4. MartinMa_

    MartinMa_

    Joined:
    Jan 3, 2021
    Posts:
    455
    From my experience no matter what value I change on serialized field, value from inspector is always used, so if you set 4 items to your list there just will be 4 items. If you use Rider Ide it is displayed next to serializedField ,
     

    Attached Files:

  5. AndrewAtCandlelight

    AndrewAtCandlelight

    Joined:
    May 3, 2022
    Posts:
    7
    Think I solved it, thanks all!

    FWIW: the trivial example I posted should work just fine. Another part of my code seems to have been the source of the error.
     
    Bunny83 likes this.
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,749
    Ah yes, been there, done that... :)

    Let me offer you these thoughts:

    One must work through the six stages of debugging:

    DENIAL. That can’t happen.
    FRUSTRATION. That doesn’t happen on my machine.
    DISBELIEF. That shouldn’t happen.
    TESTING. Why does that happen?
    GOTCHA. Oh, I see.
    RELIEF. How did that ever work?

    You may laugh now, but it will really seem hilarious to you after the 1000th time it happens.
     
    Bunny83 likes this.