- Home /
Bind to OnWillSaveAssets and force to save my scene
What I want to do: any time when someone hit Ctrl+S I want search all scenes for a specific components, run some method on them and then force to save scenes with this components along with other assets, to save state of this components.
First of all, I mark those components dirty to save changes of them specifically EditorUtility.SetDirty(component);
I tried to modify string[] paths in OnWillSaveAssets and add scenes paths. This idea not working. Every time on save I've got a "The open scenes have been modified externally" popup and asks to reload this scene or ignore. On reload it restores previous, unsaved state of the scene, on Ignore it keeps scene dirty like nothing was saved... Just in case, code I wrote:
private static string[] OnWillSaveAssets(string[] paths)
{
if (!IsEnabled) return paths;
var toPrepare = MyExtensions.FindObjectsOfInterfaceAsComponents<IPrepare>();
HashSet<string> modifiedScenes = null;
foreach (var prepare in toPrepare)
{
bool changed = prepare.Interface.Prepare();
if (changed && prepare.Component != null)
{
if (modifiedScenes == null) modifiedScenes = new HashSet<string>();
modifiedScenes.Add(prepare.Component.gameObject.scene.path);
EditorUtility.SetDirty(prepare.Component);
Debug.Log(prepare.Component.name + "." + prepare.Component.GetType().Name + ": Changed on Prepare", prepare.Component);
}
}
if (modifiedScenes != null)
{
for (var i = 0; i < paths.Length; i++) modifiedScenes.Add(paths[i]);
}
return modifiedScenes == null ? paths : modifiedScenes.ToArray();
}
Another thing I tried is to call EditorSceneManager.SaveScenes in there, but of course this will cause infinite loop so I added boolean field to check, if EditorSceneManager.SaveScenes, wi'll set it to true and in next call of OnWillSaveAssets (which is right away) this field just sets to false and no additional logic performed. But somehow this doesn't work (infinite loop persists), probably OnWillSaveAssets called several times or I don't know.
I know this is quite a niche question, didn't found a thing on this topic :(