Write cached Material and Scriptable Objects to disk on lost focus SOLVED

Unity doesn’t write content of changed Material, and ScriptableObject data files immediately, and usually needs File > Save Project to do so.

The problem is with VCS: if a non-technical person wants to create a commit right after modifying a ScriptableObject file, Unity might not write the changed file to the disk, so VCS program won’t send the updated data.

It would be ideal if Unity wrote all the cached files into SO and Material .meta files when it loses focus (it may assume the developer switched to VCS program to create a commit).

You could add an editor script that reacts to the focusChanged event.

Then call AssetDatabase.SaveAssets.

It’s absolutely maddening. It’s an irritating wart that EVERY single Unity developer using source control has to deal with every single time they change an asset.

It’s even more irritating considering 99% of people are using high-performance flash-based storage.

The only bulletproof solution I’ve seen is to insist people close Unity before preparing their commit and staging their files.

Yes, it’s very sub-optimal.

1 Like

Thanks, so the solution is (put it into Editor folder):

using UnityEditor;
using UnityEngine;

///<summary>
///Autosave on focus lost so VCS detects changes in e.g. SO changed
///</summary>
[InitializeOnLoad]
public static class AutoSaveOnFocusLost
{
    static AutoSaveOnFocusLost()
    {
        EditorApplication.focusChanged += OnFocusChanged;
    }

    private static void OnFocusChanged(bool hasFocus)
    {
        if (!hasFocus)
        {
            AssetDatabase.SaveAssets();
            Debug.Log("Unity lost focus, assets saved.");
        }
    }
}
1 Like