I try to optimize an object set in my project using the ISerializationCallbackReceiver to transform a list into a dictionary. However, some values, keys to be explicit, are null after deserialization despite not being null in the inspector. Here is a simplified setup of mine:
public class MyKeyClass : ScriptableObject { /*...*/ }
// instances of MyValueObject are instances of derived classes of MyValueObject.
[Serializable]
public abstract class MyValueObject : ScriptableObject {
public abstract MyKeyObject Key { get; }
}
My set looks like this:
public class ObjectSet : ScriptableObject, ISerializationCallbackReceiver
{
[SerializeField]
private List<MyValueObject> objects= new List<MyValueObject>();
[SerializeField]
private Dictionary<MyKeyObject, MyValueObject> indexedObjects = null;
public void OnAfterDeserialize()
{
indexedObjects = new Dictionary<Feature, BaseConstraint>();
MyValueObject item;
for (int index = 0; index < objects.Count; index++)
{
item = objects[index];
if (item != null)
{
if (!indexedObjects.ContainsKey(item.Key))
{
indexedObjects.Add(item.Key, item);
}
}
}
}
public void OnBeforeSerialize()
{
constraints.Clear();
for (int index = 0; index < indexedObjects.Count; index++)
{
constraints.Add(indexedObjects.ElementAt(index).Value);
}
/* WORKAROUND: This always adds a null item to the list in the inspector to allow adding more values,
* however, it is not included in the dictionary after deserialization.
*/
constraints.Add(null);
}
However, in the editor I get the following error code in the console:
Why are the referenced keys, accessed through the property from the abstract base class, of my objects of type MyValueObject
from my list null, whereas they show properly in the inspector, once I try to reference and index them into my dictionary after deserialization? They look fine in the inspector and my project files.
In other words, I have a collection of ScriptableObjects which each have a reference to another ScriptableObject of a different type, which can be accessed through a property, but doing so returns a null value during deserialization.