[CustomEditor(typeof(Test))]
[CanEditMultipleObjects]
public class TestInspector : Editor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(serializedObject.FindProperty("Flag1Enabled"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("Flag2Enabled"));
if(GUILayout.Button("Apply changes"))
{
serializedObject.ApplyModifiedProperties();
}
if(GUILayout.Button("Discard changes"))
{
//Assuming what I think this is doing which is reset all unapplied modifications?
serializedObject.Update();
}
}
}
The issue I am facing with the above code is that the Inspector UI does not get updated when Flag1Enabled or Flag2Enabled toggles are interacted with. The UI only gets updated when serializedObject.ApplyModifiedProperties() is called at the end of the OnInspectorGUI method which messes with my goal i.e. I only want changes to be applied to the S.O. asset on clicking "Save changes" button.
I also thought of creating a copy of the serialized object and making edits to the duplicate object - maybe this is a/the way but looking for simple solutions.
I'm pretty new to Unity - perhaps, I am making this more complicated that it needs to be?
Yesn't. It is a bit more complicated with editor scripting and serialization. You have to think frame-wise.
Within one call of
OnInspectorGUIyou havetarget)serializedObjectwhich is basically a virtual "in-between" transfer object between the Inspector and the assetSerializedPropertys which as part of theserializedObjectare also sort of a staging areaNow when you call
serializedObject.Updateyou load the current values from thetarget(c# instance) values into the stagingSerializedProperty.When you call
ApplyModifiedPropertiesit accordingly applies those back to the actual asset and triggers all sort of other secondary functionalities like dirty-marking (= saving as Unity only writes assets to disk that are marked as dirty), Undo/Redo etc.You could of course use some "manual" staging system like e.g. this
but this might become quite uncanny in more complex types.