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

Resolved Serializing a collection of ISerializationCallbackReceivers

Discussion in 'Scripting' started by nikofon007, Jul 9, 2023.

  1. nikofon007

    nikofon007

    Joined:
    Sep 10, 2020
    Posts:
    26
    I have a class that implements ISerializationCallbackReceiver. When I serialize an instance of it, it works as expected. But when I try to serialize/deserialize a List of this class neither OnBeforeSerialization, nor
    OnAfterDeserialize are called for any instance in the List. Is it intended behaviour or is it a bug?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    How are you serialising and deserialising this collection?

    Note that the interface only means anything in the context of Unity. Other serialisers know nothing about this interface.

    I've had instances where I manually call the methods of
    ISerializationCallbackReceiver
    to ensure the data has been converted to a Unity friendly form and back again in such cases.
     
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,494
    You really should show how your class looks like. I assume it's a plain Serializable data class? Not a MonoBehaviour or ScriptableObject? Because those are serialized on their own and a list of such instances would only serialize the reference to those objects which in most cases doesn't make sense except inside the Unity editor.

    If your class is too big or is somehow "classified" so you can not show it here, can you make a small reproduction case? Though keep in mind that the base class can play an important role.

    Also note that when you use Unity's JsonUtility for serialization, it does not support arrays as root objects. It always requires an object as root element that is actually serialized.
     
    nikofon007 and spiney199 like this.
  4. nikofon007

    nikofon007

    Joined:
    Sep 10, 2020
    Posts:
    26
    You actually solved my problem. Indeed I was trying to use JsonUtility to directly serialize a List of objects, even though it was stated in the documentation (which I didn't check at the time) that it doesn't work. I was too used to working with newtonsoft, and just for some reason assumed that unity worked the same way.
    Thank you!
     
    Bunny83 likes this.