Perform action on save/load in editor

Is there some way to get an editor script callback BEFORE the user saves a scene (i.e. just before the scene is written to disk), and AFTER the user loads a scene (i.e. after the scene’s objects have been loaded in the editor, but before the user makes any changes)?

I want to write a script to validate the scene (and possible modify it) in these two situations, but don’t know how to trigger my script.

Performing actions before saving a scene can be done by writing a custom AssetModificationProcessor:

http://docs.unity3d.com/Documentation/ScriptReference/AssetModificationProcessor.OnWillSaveAssets.html

Here’s an example of how we did it:

public class MyAssetModificationProcessor : AssetModificationProcessor
{
    public static string[] OnWillSaveAssets(string[] paths)
    {
        // Get the name of the scene to save.
        string scenePath = string.Empty;
        string sceneName = string.Empty;

        foreach (string path in paths)
        {
            if (path.Contains(".unity"))
            {
                scenePath = Path.GetDirectoryName(path);
                sceneName = Path.GetFileNameWithoutExtension(path);
            }
        }

        if (sceneName.Length == 0)
        {
            return paths;
        }

        // do stuff

        return paths;
    }
}

OnWillSaveAssets will be called every time the user saves the current scene, and you’re unable to switch scenes without saving or abandoning all changes. Thus, there ought to be exactly zero or one scene in the paths array.

If you want Unity not to save any of the modified assets, you can modify the paths array before returning it.

However, changing a scene before it is loaded can’t be done this way and I’m interested in how to do that without introducing a special menu item, too…

Not sure, but why not create your own menu item or window that does the save and ask your team to use that. See http://unity3d.com/support/documentation/ScriptReference/EditorApplication.SaveScene.html for ideas.