Serialized Array Initialization

  • If you have a single serialized field of a custom type in your script, Unity will properly run its field initializers and constructor to set up its default values when you add that script to an object.
  • But if the field is an array, then it won't ever run them.
    • The array starts empty by default.
    • If you resize it from empty to any other size, all the new elements will start at the default values for their type. For example, if you are resizing an array of MyClass which has a public float value = 5; field, then the value field will initialize to the default float value of 0 instead of executing the field initializer to set it to 5.
    • If you increase its size after it already has elements, the new elements will all be copied from the last existing element.
  • This means that an array of Transitions would not start with the proper default values so their Fade Duration and Speed will both be 0 instead of defaulting to 0.25 and 1 respectively.
    • The TransitionDrawer class has a workaround for this issue: if all the fields of a transition are at the default values of their type (i.e. Fade Duration and Speed at 0 rather than the 0.25 and 1 set by their field initializers) when assigning its main object (i.e. the AnimationClip for a ClipTransition), it will initialize the values properly.
    • The Serialization.IsDefaultValueByType and ResetValue methods can be used to implement similar behaviour in your own custom editor scripts, but it doesn't seem to be possible to standardise a reliable workaround for all custom classes.
  • Bug Report Case Number: 907333 - Closed and won't fix because Unity doesn't want to fix their serialization system.