- Home /
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.
I would read the blog post about the introduction to ISerializationCallbackReceiver, there are a LOT of gotcha's depending on how you construct objects, what they derive from and whether unity is going to just (de)serialize ad nauseam to ensure the internal stream has the newest information. If you go through the comments on the blog post they explain quite a bit, this includes sixtrillionbillion calls and why it may be happening.
Answer by Bunny83 · Jul 23, 2017 at 09:29 AM
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.