List.Remove(object) - unexpected behavior when used in [Serializable] class

Hello all!

quick and abbreviated version of the problem:

[Serializable]
public class SavedGameData
{
    public List<SavedItem> inventory;
}

[System.Serializable]
public struct SavedItem
{
    public string itemName;
    public string id;
    public Item.Quality quality;
    public Item.Type type;
    public int level;
    public int count;
}

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!

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://discussions.unity.com/t/799896/4

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

https://discussions.unity.com/t/870022/6

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

https://discussions.unity.com/t/892140/8

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() on a GameObject instance, or use ScriptableObject.CreateInstance() 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://discussions.unity.com/t/826141/4

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://discussions.unity.com/t/908126/3

Lots of good info in there, thanks!

^ this was exactly the next thing I tried

        List<SavedItem> updatedList = new List<SavedItem>();
        for (int i = 0; i < inventory.Count; i++)
        {
            if (inventory[i].id != item.id)
            {
                updatedList.Add(item);
            }
        }
        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)

    public void LocalSave()
    {
        savedGameData.lastSaveTime_ticks = DateTime.Now.Ticks;
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(GetPath() + "/SavedGame.dat");
        bf.Serialize(file, savedGameData);
        file.Close();
    }

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 ,

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.

1 Like

Ah yes, been there, done that… :slight_smile:

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.

2 Likes