- Home /
ISerializationCallbackReceiver not working on ScriptableObject
Hi! I use Unity 2019.1.8f1.
My problem is that I can't serialize a list of instances of objects that derive from an abstract class. I wrote this code to make it work:
[Serializable]
public abstract class MyAction { }
[Serializable]
public class MyActionA : MyAction { }
[Serializable]
public class MyActionB : MyAction { }
[Serializable]
public class MyActionsDatabase : ScriptableObject, ISerializationCallbackReceiver
{
[SerializeField]
private List<MyAction> actions = new List<MyAction>();
[SerializeField]
byte[] actionsBuffer;
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
this.actions = GenericSerializer.BinarySerializer<List<MyAction>>.Deserialize(this.actionsBuffer);
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
this.actionsBuffer = GenericSerializer.BinarySerializer<List<MyAction>>.Serialize(this.actions);
}
}
PS: GenericSerializer.BinarySerializer is a wrapper for the "BinaryFormatter" of .NET
Even though this works for MonoBehaviours, it doesn't for ScriptableObjects. I simply Add my actions to the list from an editor script and it seems ok (the buffer is serialized), then i close and reopen unity (or just change scene and return to the previous) but my buffer is empty.
The question is: does "ISerializationCallbackReceiver" work for ScriptableObjects? What could I do in order to serialize my list?
Thank you.
Answer by Bunny83 · Jul 26, 2019 at 02:24 PM
The ISerializationCallbackReceiver works for all serialized objects, even custom serializable classes, so not only MonoBehaviour and ScriptableObject derived classes.
Though it might depends on if you actually serialize your ScriptableObject correctly. How and where do you create the instances of your classes? Did you communicate that change to Unity? Did you use the Undo class?
Note since you serialize your class tree manually into a byte array you should remove the SerializeField attribute on your "actions " list since Unity can not serialize this properly and this will most likely cause all sorts of issues with the serializer.
ps: You don't have to mark ScriptableObject as Serializable as they are always serializable.
Answer by Phobetor · Jul 26, 2019 at 02:56 PM
Ok, You told me important things I didn't know!
As you suggested, I removed the "Serializable" attribute from the scriptable object, then I removed the "SerializeField" attribute from the list, but nothing changed...
Instead, I think I was not saving the "MyActionsDatabase" script from its customeditor script. Now it works well, it was my fault! xD
Thank you very much!
Your answer
![](https://koobas.hobune.stream/wayback/20220612205544im_/https://answers.unity.com/themes/thub/images/avi.jpg)