Skip to content

Instantly share code, notes, and snippets.

@gamefish
Last active July 5, 2023 01:16
Show Gist options
  • Save gamefish/cf2444d74f8b59ea40baae0c1c17b934 to your computer and use it in GitHub Desktop.
Save gamefish/cf2444d74f8b59ea40baae0c1c17b934 to your computer and use it in GitHub Desktop.
[Auto compile scripts at background] Let Unity editor auto compile scripts in background if any of scripts has been modified #unity #editor #compile #building
#if UNITY_EDITOR
using System.IO;
using System.Threading;
using UnityEditor;
/// <summary>
/// use fswatch to monitor Scripts folder,start auto compile in background before Unity gets focused
/// for Mac users, use: 'brew install fswatch' to install fswatch
/// </summary>
[InitializeOnLoad]
public class ScriptFileWatcher
{
public static string ScriptPath = "Assets/Scripts";
public static bool SetRefresh;
static ScriptFileWatcher()
{
ThreadPool.QueueUserWorkItem(MonitorDirectory, ScriptPath);
EditorApplication.update += OnUpdate;
}
private static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
SetRefresh = true;
}
private static void MonitorDirectory(object obj)
{
string path = (string)obj;
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Path = path;
fileSystemWatcher.IncludeSubdirectories = true;
fileSystemWatcher.Changed += FileSystemWatcher_Changed;
fileSystemWatcher.Created += FileSystemWatcher_Changed;
fileSystemWatcher.Renamed += FileSystemWatcher_Changed;
fileSystemWatcher.Deleted += FileSystemWatcher_Changed;
fileSystemWatcher.EnableRaisingEvents = true;
}
private static void OnUpdate()
{
if (!SetRefresh) return;
if (EditorApplication.isCompiling) return;
if (EditorApplication.isUpdating) return;
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport & ImportAssetOptions.ForceUpdate);
AssetDatabase.ImportAsset(ScriptPath, ImportAssetOptions.ForceSynchronousImport & ImportAssetOptions.ForceUpdate);
SetRefresh = false;
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment