0
\$\begingroup\$

I have a script like this:

public class A: MonoBehaviour {
   public bool x = false;
}

... and a Custom Editor like this:

[CustomEditor(typeof(A))]
public class A_E: Editor
{
   public override void OnInspectorGUI()
   {
      A a= target as A;
      if (a== null || a.gameObject == null) return;
      a.x = !EditorGUILayout.Toggle("x", !a.x);
   }
}

When I enter play mode, the property resets.

I tried fixing it by adding:

if(GUI.changed) EditorUtility.SetDirty(a);

However this only fixed it for play mode.
If I save and close the scene, it resets to the default.
Also, the scene is not set to dirty, if I make changes to the component through the custom editor.

\$\endgroup\$
2
\$\begingroup\$

You'll notice the docs for SetDirty point out that this method has been replaced:

Prior to Unity 5.3, this was the primary method of marking objects as dirty. From 5.3 onwards, with the introduction of Multi-Scene Editing, this function should no-longer be used for modifying objects in scenes. Instead, you should use Undo.RecordObject prior to making changes to the object. This will mark the object's scene as dirty and provide an undo entry in the editor.

Here's how your code would look with this pattern:

public override void OnInspectorGUI() { 
    A a= target as A; 

    if (a== null || a.gameObject == null) 
         return; 

    EditorGUI.BeginChangeCheck();
    bool x = !EditorGUILayout.Toggle("x", !a.x); 
    if(EditorGUI.EndChangeCheck()) {
        Undo.RecordObject(target, "Changed x");
        a.x = x;
    }
}
\$\endgroup\$
  • \$\begingroup\$ Ah...thanks! I already changed my editor scripts to use serializedObject.FindProperty("myProperty");, EditorGUILayout.PropertyField(myProperty, new GUIContent("My Property")); and serializedObject.ApplyModifiedProperties();. \$\endgroup\$ – 000000000000000000000 Sep 20 '17 at 19:03
  • \$\begingroup\$ Feel free to add that as another answer, as it's also a completely valid way to handle serialization. \$\endgroup\$ – DMGregory Sep 20 '17 at 19:04
0
\$\begingroup\$

Here's another solution that I ultimately went with:

[CustomEditor(typeof(A))]
public class A_E: Editor
{
   private SerializedProperty x;

   public OnEnable(){
      x = serializedObject.FindProperty("x");
   }

   public override void OnInspectorGUI()
   {
      serializedObject.Update();
      x.boolValue = !EditorGUILayout.Toggle("x", !x.boolValue);
      serializedObject.ApplyModifiedProperties();
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.