Serialization replacing null object in array with empty object

I have this in my scriptable object:

[SerializeField]
public AnimationCurve[] scaleCurves;

In my original object, some of the array elements are null.

When I load this object later, all my null curves have been replaced with animation curves that evaluate to 0.0.

This happens in Unity 2019.4.36f LTS.

Here’s how the serialized array looks like with 3 null curves in it:

  scaleCurves:
  - serializedVersion: 2
    m_Curve: []
    m_PreInfinity: 2
    m_PostInfinity: 2
    m_RotationOrder: 4
  - serializedVersion: 2
    m_Curve: []
    m_PreInfinity: 2
    m_PostInfinity: 2
    m_RotationOrder: 4
  - serializedVersion: 2
    m_Curve: []
    m_PreInfinity: 2
    m_PostInfinity: 2
    m_RotationOrder: 4

So I’m guessing that’s the issue - since array element is null, serialization creates 3 empty entries in asset file. Then, during deserialization it actually creates these objects, but does not fill them with any data.

If you have problems reproducing it, let me know.

This is a result of the fact that Unity’s serialization does not support null. If you need to know that an AnimationCurve or any object actually exists or not, you can use a bool field like “hasAnimationCurve”.

Details about Unity serialization can be found here: Unity - Manual: Script serialization including documentation on the lack of support for null:

2 Likes

Tanks for your reply. I kinda suspected something like that (that having nulls in my array is “illegal practice” :slight_smile: )

I’ve changed thread tag to “resolved”. Although it would be nice to get a warning message when you serialize something that is not appropriate for serialization - especially if the process will alter your data structures

1 Like