- Home /
How to use the Undo class to record editor script property changes?
The issue is fairly obvious
EditorGUI.BeginChangeCheck();
myFloat= EditorGUILayout.Slider("Slider", myFloat, -3, 3);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(this, "float");
EditorUtility.SetDirty(this);
}
Since we already changed the value myFloat it doesn't make much sense to call Undo.RecordObject() - but we shouldn't call it before that either because the EditorGUILayout.Slider() is changing it every frame basically regardless of user input). Is there a built in way to support undo/redo in editor scripts or do I have to manually create another variable for every variable I want to modify?
Answer by Pecek · Apr 15, 2018 at 11:05 AM
The EditorUndoManager from the wiki worked well after some slight modifications(it's kind of expected as it's 7 years old at this point). If anyone is interested here is the link
http://wiki.unity3d.com/index.php?title=EditorUndoManager
I removed the obsolete stuff and changed them to Undo.RegisterCompleteObjectUndo(). Also the properties have to be either public or marked as [Serialized](it sounds obvious as I type it but it took me a good 20 minutes to figure out why does it work with some of my changes while it doesn't with others).
Thanks! So the trick indeed was adding [SerializeField] and ensuring the types are using [Serialized] attribute, inside the editor script. I use them all the time for monobehaviors, but writing these attributes directly inside the editor script is kind of unusual to me :D
You can also use "[SerializeField] [HideInInspector]" if you still want to hide it and to be private
Right, I mentioned this combination at the end of my answer over here. The table I created is ordered by precedence from top to bottom. So if multiple things apply, things at the top would overwrite things further down.
Answer by SmushyTaco · May 08, 2020 at 07:02 AM
If you don't want to rely on 3rd party code you could do the following:
EditorGUI.BeginChangeCheck();
var myFloatForUndoCheck = myFloat;
myFloatForUndoCheck = EditorGUILayout.Slider("Slider", myFloatForUndoCheck, -3, 3);
if (EditorGUI.EndChangeCheck()) {
Undo.RecordObject(this, "My Float");
myFloat = myFloatForUndoCheck;
}
Your answer
Follow this Question
Related Questions
Why is play mode reverting my scriptableobject to a previous serialized state? 2 Answers
Undo.RecordObject is too slow on large arrays, alternatives? 1 Answer
Undo SetSiblingIndex for root objects? 1 Answer
How to undo removing components in an editor extension? 0 Answers
Is there a way to register undo for all ColorField changes, or name the individual undos? 0 Answers