- Home /
How to support undo for objects in .asset files
Hi, I'm creating an asset using the following code:
[MenuItem("Assets/Create/Graph")]
public static void CreateAssetGraph()
{
var asset = ScriptableObject.CreateInstance<Graph>();
AssetDatabase.CreateAsset(asset, AssetDatabase.GenerateUniqueAssetPath("Assets/NewGraph.asset"));
AssetDatabase.SetLabels(asset, new string[] { "Graph" });
AssetDatabase.SaveAssets();
}
I want to support Undo for all the operations performed on this asset so I'm writing the following before each operation:
Undo.RecordObject(activeGraph, string.Format("Create {0} Block", blockShape.Name));
The issue is that, after I undo the operation, my object doesn't seem to change.
I added handlers to ValidateCommand and ExecuteCommand events so that when I get a command name "UndoRedoPerformed" I execute:
EditorUtility.SetDirty(activeGraph);
AssetDatabase.SaveAssets();
I can see then in the .asset file that the undo was performed and correctly serialized. I tried using AssetDatabase.ImportAsset and AssetDatabase.Refresh and the version in memory never changes. If I close Unity and reopen the project, then the .asset is loaded correctly.
Am I missing something?
Thanks in advance, Antao
I'm afraid I don't have an answer, but I currently have Undo working for all of my assets, and I'm doing pretty similar things. Here are some ideas:
First off, you want to use SerializiedObject/Serialized property whenever possible. In cases where you can't, then it should be sufficient to record the object, make the change, and then call EditorUtility.SetDirty.
You may need to call Repaint() when the undo happens, depending on where you are drawing the asset properties. The GUI sometimes updates infrequently, which makes it look like your actions had no effect.
You don't need to manually call SaveAssets, unless you are afraid of Unity crashing. $$anonymous$$arking the asset as dirty will (should) let Unity know to save that asset whenever it needs to (like exiting the app).
Answer by aalmada · Feb 16, 2014 at 06:57 PM
I decided to create a simpler project to test these issues. The source is available at https://bitbucket.org/aalmada/assetdemo. I'm still not happy with the editor window not updating when not in focus but I got most of it working. Antao
Any chance you could give a breakdown of what's going on in your scripts in that link? There are a number of similar questions to this one and virtually nothing in Unity's documentation or examples to help out some of us who are less experienced with editor scripting.