EditorGUILayout.PropertyField in Custom EditorWindow Shows Wrong Text On Focus

In a custom editor window, I have an EditorGUILayout.PropertyField showing one of two possible instances of a MonoBehaviour using a SerializedObject. The script that the PropertyField shows is controlled by a button that toggles one of the two scripts. The script only has one public string variable, Text.

When I open the window, I can see the property field (as a text field) and the toggle button, and pressing the button will make the text in the property field change like intended. But if I focus the text field and then press the toggle button, the text won’t change. Then, if I click outside the window to unfocus it, the text suddenly changes. If I click back to the window to the text field, the text changes to the wrong value again. Basically, the field has the wrong text while it is focused until I change the text or click on another text field or other similar control (like a Game Object in the hierarchy or so).

Am I using the SerializedObject/SerializedProperty/PropertyField wrong? I tried logging the values of the SerializedProperty while the field is showing the wrong text, but it seems the SerializedProperty always holds the correct value.

Here’s the code for my editor window:

public class PropertyFieldEditorWindow : EditorWindow
{
    Property property1 = null;
    Property property2 = null;

    bool toggle = true;

    [MenuItem("Window/Property Field Window")]
    public static void ShowWindow()
    {
        PropertyFieldEditorWindow window = GetWindow<PropertyFieldEditorWindow>("Item Database");

        GameObject gameObject1 = new GameObject("GameObject 1");
        Property firstProperty = gameObject1.AddComponent<Property>();
        firstProperty.Text = "First text!";
        window.property1 = firstProperty;

        GameObject gameObject2 = new GameObject("GameObject 2");
        Property secondProperty = gameObject2.AddComponent<Property>();
        secondProperty.Text = "Second text!";
        window.property2 = secondProperty;
    }

    private void OnGUI()
    {
        Property property = null;

        if (toggle)
            property = property1;

        else
            property = property2;

        SerializedObject serializedObject = new SerializedObject(property);
        SerializedProperty textProperty = serializedObject.FindProperty("Text");
        EditorGUILayout.PropertyField(textProperty);

        serializedObject.ApplyModifiedProperties();

        if (GUILayout.Button("Toggle"))
            toggle = !toggle;
    }
}

And the Property script:

public class Property : MonoBehaviour
{
    public string Text = "";
}

if (GUILayout.Button(“Toggle”)) {
GUI.FocusControl(“”);
toggle = !toggle;
}
this should solve your problem