OnValidate changed fields doesnt save after exit the play mode.

Hello. I have the next code (simplified)

public class MapComponent : MonoBehaviour
     /* Many other fields  - settings*/
	public GameObject tilePivot;
	void OnValidate()
		if (Application.isPlaying) return;
        else if( /* Settings changed */)Regenerate();

	private void Regenerate()
		if (tilePivot != null) {
		tilePivot = new GameObject("Map");

When im spawn object in editor, it use regenerate() method to make himself and spawn child objects.
Child objects saving as childrens of a “tilePivot”.
On some parameter changes, script use tilePivot to remove all child objects, and spawn they again.
In editor everything work nice.

When im enter to play mode, “tilePivot” value becomes null, but child objects still exists, and at this step everything wok as expected, because object dosent need changes in playmode.

But after exit the play mode, tilePivot is still null and im getting a duplicated objects at next OnValidate event.

Does calling EditorUtility.SetDirty( this.gameObject ) after Regenerate() helps?

General idea is that Editor won’t always register changes to your scene/objects automagically - as a design decision. In such cases programmer is responsible for telling the editor which changes matter (to serialize/save those thus creating adequate undo steps).

More on that here: How-do-I-make-a-scene-dirty-when-modifying-a-property-via-script