I know Unity has some problematic serialization issues (such as not serializing dictionaries, which is very sad), but I ran into a problem I didn’t expect I would.
Here’s the scenario:
Class 1 (Scriptable Object, serialized properly, where Bar is another class (not struct)):
public class Foo : ScriptableObject
{
public List<Bar> MyList;
}
Class 2 (pseudocode):
public class Baz : MonoBehaviour
{
public Foo reference = GetReference();
public List<Bar> BarListOrderedByX;
public void Bake()
{
for (int i = 0; i < reference.MyList.Count. i++)
{
if (reference.MyList[i].X = X)
BarListOrderedByX.Add(reference.MyList[i]);
}
}
}
Long story short, I have a list of reference type objects, and then I have multiple other lists with those objects either ordered by something, or with some specific condition, just a way to browse through those objects MUCH faster then checking the conditions in real time.
Problem is… instead of the indexing lists using a REFERENCE to the original object… they are actively cloning the object, apparently for serialization purposes… and aside from the obvious problem that if you edit one the other doesnt receive the changes, the file size gets HUGE, which is exactly what Im trying to keep low.
So, anyone has any idea of why this is happening and if there is anything that can be done about it?
At first we had each item as a separate scriptable object, and while practical, it is problematic for the amount of items we have, and even more considering that this is going to be expanded for a long time. We had over 10mb of item scriptable objects, which were on RAM at all times since we didnt want to keep referencing them by name somewhere to find them in run time.
So if that is the case, what would be the best way to store thousands of items and have them easily accessed during gameplay? We have about a thousand items, but what if we had 10 thousand items or whatever, even bigger numbers of items?
By the way, from transforming the list of items from multiple scriptable objects to one scriptable object with a list, we reduced file size from 12mb to 1mb…
I would recommend you to figure out how Unity’s serialization format works. It’s not too complex - just open the scriptable object in a text editor. That’ll make working with it a lot easier.
You’re going to either live with very big files, or do some manual bookkeeping. Using the ISerializationCallbackReceiver interface, you can get messages from Unity when your objects are serialized and deserialized. If your Bar objects has an unique identifier, you’ll want to ditch the Bar references on serialize time, and serialize the ID’s instead. On deserialization, you can swap the ID’s for the objects again.
I’ve done similar things with linked structures (ie. trees), and it works pretty well