Last active
July 5, 2023 01:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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