I’m not sure if I’m doing something wrong but after upgrading to 5.6b it just stopped working as expected. Yes, I’ve read the release notes where it says that “OnAfterDeserialize is only invoked once” now, yet it’s somewhat vague as to how you should upgrade your code.
Here’s a simple class I wrote:
using UnityEngine;
using System.Collections.Generic;
public class SerializationTest : MonoBehaviour, ISerializationCallbackReceiver
{
public Dictionary<string, object> Dict = new Dictionary<string, object>();
[SerializeField] private List<string> _keys = new List<string>();
[SerializeField] private List<object> _values = new List<object>();
public void OnBeforeSerialize()
{
_keys.Clear();
_values.Clear();
foreach (var kvp in Dict) {
_keys.Add(kvp.Key);
_values.Add(kvp.Value);
}
Debug.Log("OnBeforeSerialize: " + GetHashCode() + " " + Dict.Count);
}
public void OnAfterDeserialize()
{
Dict.Clear();
var count = _keys.Count;
for (var i = 0; i < count; i++)
Dict.Add(_keys[i], _values[i]);
Debug.Log("OnAfterDeserialize: " + GetHashCode() + " " + _keys.Count);
}
}
Now when I try to Instantiate the prefab I get this:
OnBeforeSerialize: 218386 138
OnBeforeSerialize: -19264 0
OnAfterDeserialize: -19264 0
218386 is the hash code of the original prefab.
-19264 is the hash code of a new script instance.
For some reason OnBeforeSerialize is called for the new instance before OnAfterDeserialize so the lists get overwritten.
Is this how it’s supposed to work now or is it a bug?
Should I somehow check each time if the “non-serializable fields” are empty and not do the serialization?