After setting a field using the editor API, the field gets cleared on Play in Unity. How to fix it?
I have a menu item. That menu item sets a field on one of my game objects in scene. After the field was set I can see the correct value in editor and I save the scene. But whenever I Play my game from the editor the field gets reset to a default value forever.
I found a brief explanation of the reasons behind that here. In a nutshell before Play Unity is serializing my whole scene and for some reasons it misses the specific field which was set through the editor API. So, later on Unity loads (i.e. creates a copy of what was serialized) the serialized scene and performs the Play itself.
All that led me to try a trick, which actually worked. First, I change the field through the editor API. After that I change another random field using the editor itself and save a scene. Then I revert the random field value and save my scene once more. Now if I Play I get the field value preserved and I get what I am asking for in this question. But this way of doing things seems like a technical debt to me, so I was hoping that someone might suggest something better.
Also, neither the
[System.Serializable], nor the
[SerializeField] properties on that field did not help.
My guess is that while the editor API is executing I need to tell it to take into account the changed field somehow after it was changed. But I was not able to find out how to do that.