Values lost on entering play mode

Hello! I’ve got a problem with variables losing their values when modified via script.

When I press the Test button in the code below, whatever string was in the MapBuilder’s value field is changed to “ASDF”, as expected. As soon as I enter Play Mode (or leave the scene - I get no prompt for saving), the value reverts back to what it was before I pressed the Test button. I’ve searched for hours about serialization but every explanation or answer I’ve encountered has been about serialization of non-native types - which I do not believe is the issue here.

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(MapBuilder))]
public class MapEditor : Editor
{
  public override void OnInspectorGUI()
  {
    DrawDefaultInspector();

    MapBuilder builder = (MapBuilder)target;

    if (GUILayout.Button("Test"))
      builder.Test();
  }
}
using UnityEngine;

public class MapBuilder : MonoBehaviour
{
  public string value;

  public void Test()
  {
    value = "ASDF";
  }
}

Any help would be appreciated!

Try calling serializedObject.Update() at the start of your OnInspectorGui() function.

I have tried that but the problem persists. I have also tried adding serializedObject.ApplyModifiedProperties(); at the end, but also to not avail.

I do not know if this is the best way, but this seems to be working, I think.

public override void OnInspectorGUI()
{
  DrawDefaultInspector();

  Test5 builder = (Test5)target;
   
   if (GUILayout.Button("Test"))
   {
      builder.Test();
      UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene());
   }
}

@methos5k While that does change the scene’s state to “modified”, it does not solve the issue of the value field reverting to its initial state, even if I save the scene.

For me, I get ‘modified’ for the scene. Loading the scene doesn’t change the value. Changing scenes prompts for a “Save?”… obviously I click ‘yes’ and it is there (the new string’s value) when I switch back to the scene.

I finally figured it out: The MapBuilder script was attached to a prefab. Of course; prefabs are all initialised to their default state at run time. No wonder I had trouble finding anyone with the same issue. I’m kicking myself for not simply testing the script on a new game object!

Thanks everyone for the assistance. Looks like that MarkSceneDirty method may come in handy after all.

Well, glad you figured it out. :slight_smile:

1 Like