OnBeforeSerialize constantly called in Editor Mode

One of my scripts which also runs in the editor (ExecuteInEditMode) requires some custom code for serialization. So I derived my class from ISerializationCallbackReceiver and implemented OnBeforeSerialize and for OnAfterDeserialize.

I noticed that the OnBeforeSerialize is constantly called serveral times per second. This happens although there are no changes on the object.

Why is this happening? I would assume that the serialization is only called when necessary (i.e. starting the game, or saving the scene).

As my serialization code is quite heavy on the CPU it should be called only if necessary.

Unity uses the serialization system for accessing the properties of an object and showing them in the inspector. That’s represented by the SerializedObject and SerializedProperty in editor code. They don’t have a direct reference to the actual object / value but represent the serialized data. So whenever the Inspector window is redrawn / updated or receives an event the serialized data need to be updated in order to show the actual values in the inspector.

It’s more or less mentioned in the blog post that Landern linked in the comment above as the second bulletpoint:

Serialization of “things” is at the
very core of Unity. Many of our
features build ontop of the
serialization system

Inspector window. The inspector window doesn’t talk to the C# api to
figure out what the values of the
properties of whatever it is
inspecting is. It asks the object to
serialize itself, and then displays
the serialized data.