DrawPropertiesExcluding resets my script's fields

Hey.

So I have a simple script attached to different gameObjects. To manage this script, I have another script which adds a button in the inspector (it helps me to fill my script’s properties).

My script :

[RequireComponent(typeof(RectTransform))]
public class APanel : MonoBehaviour {
    [HideInInspector]
    public bool m_CloseAllOtherPanels;

    public List<APanel> m_panelsToClose = new List<APanel>();
    public bool m_openAtStart;

    public Vector2 m_openAnchorMin;
    public Vector2 m_openAnchorMax;
}

The other one :

using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(APanel))]
public class APanelEditor : Editor {
    public override void OnInspectorGUI() {
        APanel myTarget = (APanel)target;
        RectTransform rectTransform = myTarget.GetComponent<RectTransform>();

        if (GUILayout.Button("Set 'Open' Data")) {
            myTarget.m_openAnchorMin = rectTransform.anchorMin;
            myTarget.m_openAnchorMax = rectTransform.anchorMax;
        }

        myTarget.m_CloseAllOtherPanels = GUILayout.Toggle(myTarget.m_CloseAllOtherPanels, "Close All Other Panels");

        if (myTarget.m_CloseAllOtherPanels) {
            DrawPropertiesExcluding(serializedObject, new string[] { "m_panelsToClose" });
        } else {
            DrawDefaultInspector();
        }

        if (GUI.changed) {
            EditorUtility.SetDirty(myTarget);
        }
    }
}

If m_CloseAllOtherPanels is unchecked, DrawDefaultInspector is called and everything’s fine. If it is checked, DrawPropertiesExcluding does what I expect in the inspector : it shows m_panelsToClose if the variable is checked.

Unfortunately, when DrawPropertiesExcluding is called, all properties from APanel aren’t saved… So If I check from the inspector m_openAtStart and if I switch from the gameObject to another one and select it again, m_openAtStart will not be checked…

I don’t think this is expected by Unity’s staff, but maybe I’m missing something ?

Thank you :slight_smile:

Sbizz.

1 Like

Don’t know if you already got a solution but maybe this will help you, add these lines to your code:

public override void OnInspectorGUI() {
    serializedObject.Update();
    // your code here
    serializedObject.ApplyModifiedProperties();
}

I hope it work.

3 Likes

You must call serializedObject.ApplyModifiedProperties() after DrawPropertiesExcluding. Weirdly, you can call it before DrawDefaultInspector(), so this cause me a lot of difficulty to find.

Thanks!! It worked for me :slight_smile:

For posterity, the reason this happens is that DrawDefaultInspector calls serializedObject.Update and serializedObject.ApplyModifiedProperties on its own