When is a field marked [SerializeReference] serialized?

Hello guys,

I am keeping polymorphic lists of abstract classes holding concrete instances of derived types at multiple locations in my code architecture.

A basic example would be

List<CharacterStat> stats

where CharacterStat is an abstract class and stats is holding instances of FlatStat, PercentStat, ResourceStat among other possibilities.

The Question

I can perfectly serialize this list into e.g. a ScriptableObject after decorating the field with [SerializeReference] using Unitys default serialization system, but I noticed, that the serialization happens at a different point in time than fields decorated with [SerializeField].

When I explicitly call EditorUtillity.SetDirty() on my ScriptableObject and then inspect the .asset file, I can see that all value-fields have been serialized, but the ones decorated with [SerializeReference] have not.

I noticed that after a script assembly reload or closing out of the editor, these fields would then be serialized.

I can not find much information about this in general, apart from the doc page for SerializeReference, which does not specify it.

I would love to know where the serialization happens, especially in order to force the serialization at a specific point in my custom editors, as i require that for my use case

  • and I do not want to manually trigger an assembly reload just to make sure my references have been serialized.*

After a bit of trial and error I found a solution to force the serialization of reference-fields ([SerializeReference]) together with value-fields ([SerializeField]) inside ScriptableObject assets.

Previously, for value-fields, it was enough to do EditorUtility.SetDirty() to serialize to disk.

After adding an AssetDatabase.SaveAssets(), I was able to also serialize reference fields to the asset file instantly.